/*
    #README#
    聪明的电教员 Alpha版
    提示： 请使用DEV C++ 6.7.5编译器进行编译，在此其他版本上运行可能会出错。
    制作公司：Mialogofind.Inc.（独创）
    原始著作人： 2106班 罗米奇（框架） &  2110班 祁文清（算法） &  2213班 李知博（辅助） & GPT。
    欢迎您改动！并进行优化与升级并发布！可私自修改（包括著作人等），但不可肆意商用，如违反，后果严重，请自负。
*/

#include<windows.h>
#include<iostream>
#include<io.h>
#include<math.h>
#include<map>
#include<algorithm>
#include<fstream>
#include<queue>
#include<iomanip>
#include<conio.h>

// 文件名定义
#define PROGRAM_FILENAME "聪明的电教员Alpha.exe"
using namespace std; //使用电脑空间的声明
string ProgramVersion = "Alpha V0.99.3f"; //电教员程序的版本号
string driveLetter = "";// 初始驱动器字母，现在是字符串，在新的字母到来之前就是空的 
string olddriveletter = "";
 
struct ShutTime { //创建结构体
	int *A; //ShutdownTime_hour,即设定的小时
	int *A2; //ShutdownTime_minute, 即设定的小时
	int *A3; //ShutdownTime_weekday, 即设定的星期
};
 
struct SleepTime {//创建结构体
	int *A; //SleepDisplayTime_hour,即设定的小时
	int *A2; //SleepDisplayTime_minute, 即设定的小时
};

bool Cmp(pair<int, int> x, pair<int, int> y) {//布尔值
	if (x.first > y.first)
		return true;
	return false;
}
 
// 磁盘信息显示函数
void showProgressBar(double usedSpace, double totalSpace, int barWidth) {
    double percentage = usedSpace / totalSpace * 100.0;
    int progress = static_cast<int>(barWidth * percentage / 100);

    // 输出磁盘信息
    std::cout << " | "
              << std::fixed << std::setprecision(2) 
              << usedSpace / (1024 * 1024 * 1024) << " GB / "
              << totalSpace / (1024 * 1024 * 1024) << " GB " << endl;

    // 输出进度条
    std::cout << " [";
    for (int i = 0; i < barWidth; i++) {
        if (i < progress)
            std::cout << "=";  // 用“=”表示已用空间
        else
            std::cout << " ";   // 空格表示剩余空间
    }
    std::cout << "]\n" << endl; // 换行
    std::cout.flush();
}
 
std::uintmax_t get_file_size(const std::string& filepath) {
	std::ifstream file(filepath, std::ios::binary | std::ios::ate);
	if (!file) {
		std::cerr << "无法打开文件: " << filepath << '\n';
		return 0;
	}
 
	std::uintmax_t size = file.tellg();
	file.close();
	return size;
}
 
std::string format_size(std::uintmax_t size) {
	static const char* suffixes[] = {" B", " KB", " MB", " GB", " TB"};
	const int numSuffixes = sizeof(suffixes) / sizeof(suffixes[0]);
 
	if (size == 0) {
		return "0B";
	}
 
	int index = static_cast<int>(std::floor(std::log(size) / std::log(1024)));
	index = std::min(index, numSuffixes - 1);
 
	double result = size / std::pow(1024, index);
	char buffer[10];
	std::snprintf(buffer, sizeof(buffer), "%.2f%s", result, suffixes[index]);
	return buffer;
}

// 辅助函数：去除字符串首尾空白
std::string trim(const std::string& str) {
    size_t first = str.find_first_not_of(" \t");
    if (std::string::npos == first) return "";
    size_t last = str.find_last_not_of(" \t");
    return str.substr(first, (last - first + 1));
}

std::string UserSetFile(const std::string& operation, const std::string& key, const std::string& value = "") {
    // 预定义配置模板（类型，键名，默认值）
    const static std::vector<std::tuple<std::string, std::string, std::string>> predefinedConfigs = {
        {"bool", "ProgramAutoStart", "T"},
        {"bool", "Autolock", "T"},
        {"bool", "SilentShutdown", "T"},
        {"bool","FirstStartMinimized","T"},
        {"bool", "NightMode", "T"},
        {"bool", "Showwindow_Thread", "T"},
        {"bool", "StartShowwin", "T"},
        {"bool", "ShutDown_Thread", "T"},
        {"bool", "SHOUTDOWN", "T"},
        {"bool", "SLEEP", "T"},
        {"bool", "REBOOT", "T"},
        {"bool", "LOCK", "T"},
        {"bool", "SlientRun", "T"},
        {"bool", "ResetShottime_Thread", "T"},
        {"bool", "Filehide", "F"},
        {"bool", "CreateLnk", "T"},
        {"bool","DarkColor","T"},
        {"bool", "AutoColor", "T"},
        {"int", "ResetShotTime", "10"},
        {"int", "ShowwindowTime", "10"},
        {"int", "ShutDownTime", "10"},
        {"int", "Autolocktime", "15"},
        {"int", "SlientRunTime", "10"},
        {"int", "ColorChangeTime", "7-17"},
        {"char", "Driveletter", "C:"},
        {"string", "ProgramVersion", ""},
        {"password", "password", ""}
    };

    // 辅助函数：获取配置文件路径
    auto getFilePath = [](const std::string& drive = "") {
        std::string usedDrive = drive.empty() ? driveLetter : drive;
        return usedDrive + "\\Clever Eletrician\\ProgramData\\UserSetting.Set";
    };

    // 辅助函数：读取并处理配置文件
    auto loadAndProcessConfig = [&](const std::string& filePath, std::vector<std::string>& lines, 
                                   std::map<std::string, size_t>& keyMap) {
        lines.clear();
        keyMap.clear();
        std::map<std::string, bool> seenKeys;

        // 读取文件并去除重复项
        std::ifstream inFile(filePath);
        if (inFile.is_open()) {
            std::string line;
            while (std::getline(inFile, line)) {
                size_t typeEnd = line.find(']');
                size_t eqPos = line.find('=');
                if (typeEnd != std::string::npos && eqPos != std::string::npos) {
                    std::string keyName = trim(line.substr(typeEnd + 1, eqPos - typeEnd - 1));
                    if (seenKeys.find(keyName) == seenKeys.end()) {
                        lines.push_back(line);
                        keyMap[keyName] = lines.size() - 1;
                        seenKeys[keyName] = true;
                    }
                } else {
                    lines.push_back(line);
                }
            }
            // 利用RAII自动关闭文件，无需显式调用close()
        }

        // 补全缺失的配置
        bool configUpdated = false;
        for (const auto& [type, name, defaultValue] : predefinedConfigs) {
            if (keyMap.find(name) == keyMap.end()) {
                std::string newLine = "[" + type + "]" + name + "=" + defaultValue;
                lines.push_back(newLine);
                keyMap[name] = lines.size() - 1;
                configUpdated = true;
            }
        }

        // 移除没有类型的项
        std::vector<std::string> validLines;
        for (const auto& line : lines) {
            if (line.find(']') != std::string::npos) {
                validLines.push_back(line);
            }
        }
        
        if (validLines.size() != lines.size()) {
            lines = validLines;
            configUpdated = true;
            // 更新keyMap
            keyMap.clear();
            for (size_t i = 0; i < lines.size(); ++i) {
                size_t typeEnd = lines[i].find(']');
                size_t eqPos = lines[i].find('=', typeEnd + 1);
                if (typeEnd != std::string::npos && eqPos != std::string::npos) {
                    std::string keyName = trim(lines[i].substr(typeEnd + 1, eqPos - typeEnd - 1));
                    keyMap[keyName] = i;
                }
            }
        }

        // 如果配置有更新，写回文件
        if (configUpdated) {
            std::ofstream outFile(filePath);
            if (outFile.is_open()) {
                for (const auto& line : lines) {
                    outFile << line << "\n";
                }
                // 利用RAII自动关闭文件
            }
        }

        return configUpdated;
    };

    // 处理GET操作
    if (operation == "GET") {
        std::vector<std::string> lines;
        std::map<std::string, size_t> keyMap;
        std::string filePath = getFilePath();
        
        loadAndProcessConfig(filePath, lines, keyMap);
        
        if (keyMap.find(key) != keyMap.end()) {
            size_t lineNum = keyMap[key];
            size_t eqPos = lines[lineNum].find('=');
            if (eqPos != std::string::npos) {
                return trim(lines[lineNum].substr(eqPos + 1));
            }
        }
        return "";
    }

    // 处理WRITE操作
    if (operation == "WRITE") {
        // 特殊处理Driveletter，需要更新所有驱动器上的配置
        if (key == "Driveletter") {
            char drives[256];
            GetLogicalDriveStringsA(sizeof(drives), drives);
            char* drive = drives;

            while (*drive) {
                std::string currentDrive = drive;
                std::string filePath = getFilePath(currentDrive);
                
                std::vector<std::string> lines;
                std::map<std::string, size_t> keyMap;
                
                loadAndProcessConfig(filePath, lines, keyMap);
                
                // 更新键值
                if (keyMap.find(key) != keyMap.end()) {
                    size_t lineNum = keyMap[key];
                    size_t typeEnd = lines[lineNum].find(']');
                    if (typeEnd != std::string::npos) {
                        std::string typePrefix = lines[lineNum].substr(0, typeEnd + 1);
                        lines[lineNum] = typePrefix + key + "=" + value;
                        
                        // 写回更新
                        std::ofstream outFile(filePath);
                        if (outFile.is_open()) {
                            for (const auto& line : lines) {
                                outFile << line << "\n";
                            }
                        }
                    }
                }
                
                drive += strlen(drive) + 1;
            }
        } else {
            std::string filePath = getFilePath();
            std::vector<std::string> lines;
            std::map<std::string, size_t> keyMap;
            
            loadAndProcessConfig(filePath, lines, keyMap);
            
            // 更新键值
            if (keyMap.find(key) != keyMap.end()) {
                size_t lineNum = keyMap[key];
                size_t typeEnd = lines[lineNum].find(']');
                if (typeEnd != std::string::npos) {
                    std::string typePrefix = lines[lineNum].substr(0, typeEnd + 1);
                    lines[lineNum] = typePrefix + key + "=" + value;
                    
                    // 写回更新
                    std::ofstream outFile(filePath);
                    if (outFile.is_open()) {
                        for (const auto& line : lines) {
                            outFile << line << "\n";
                        }
                    }
                }
            }
        }

        return "SUCCESS";
    }

    return "INVALID_OPERATION";
}


volatile bool stopShowWindowThread = false; //关机线程旗帜
bool ShutFirst = false;
int OnlyRunShutThread = 0;

 
DWORD WINAPI Showwindow_Thread(LPVOID) {
    // 初始检查线程是否启用
    if (UserSetFile("GET", "Showwindow_Thread") != "T") {
        return 0;
    }

    // 初始化变量
    LASTINPUTINFO lii = {0};
    lii.cbSize = sizeof(LASTINPUTINFO);
    int showWindowTime = 10; // 默认10秒
    bool isMinimized = false; // 记录窗口状态，避免重复操作

    while (!stopShowWindowThread) {
        // 每秒检查一次配置（确保实时性）
        // 1. 检查线程是否被禁用
        if (UserSetFile("GET", "Showwindow_Thread") != "T") {
            break;
        }

        // 2. 更新窗口超时时间（添加异常处理）
        std::string timeStr = UserSetFile("GET", "ShowwindowTime");
        try {
            showWindowTime = std::stoi(timeStr);
        } catch (...) {
            showWindowTime = 10; // 转换失败时使用默认值
        }

        // 3. 获取用户最后输入时间
        if (!GetLastInputInfo(&lii)) {
            Sleep(1000); // 获取失败，休眠1秒重试
            continue;
        }

        // 4. 计算无操作时间并判断是否需要最小化
        DWORD idleTime = GetTickCount() - lii.dwTime;
        if (idleTime > static_cast<DWORD>(abs(showWindowTime)) * 1000) {
            if (!isMinimized) {
                // 最小化窗口并移除关闭菜单（仅在状态变化时执行一次）
                ShowWindow(GetConsoleWindow(), SW_MINIMIZE);
                DeleteMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE, MF_BYCOMMAND);
                DrawMenuBar(GetConsoleWindow());
                isMinimized = true;
            }
        } else {
            isMinimized = false; // 有操作，重置状态
        }

        Sleep(1000); // 每秒循环一次，保证实时性
    }

    return 0;
}

DWORD WINAPI AutoLock_Thread(LPVOID) {
    if (UserSetFile("GET", "LOCK") == "T") {
        LASTINPUTINFO lii;
        lii.cbSize = sizeof(LASTINPUTINFO);
        int LockProgram = std::stoi(UserSetFile("GET", "Autolocktime"));
        for (int i = LockProgram * 60; i > 0; i--) {
		    Sleep(1000); // 每秒暂停 1 秒，可测试UserSet()函数的稳定性
		    //cout << i << " seconds remaining" << endl; // 测试用，打印剩余时间
		    // 检查条件：如果 `UserSet(Setkey)` 为 1 或 `UserSet(12)` 与 `LockProgram` 不同，则退出循环
		    if (UserSetFile("GET", "LOCK") == "F" || std::stoi(UserSetFile("GET", "Autolocktime")) != LockProgram) {
		        return 0;  // 条件满足，线程结束
		    }
		}
		
        // 重新启动程序
        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        ZeroMemory(&pi, sizeof(pi));

        // 获取当前可执行文件的路径
        char szFilePath[MAX_PATH];
        GetModuleFileName(NULL, szFilePath, MAX_PATH);

        // 创建新进程以重新启动程序
        if (!CreateProcess(szFilePath, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            printf("程序重新启动失败，错误代码: %d\n", GetLastError());
            return 0;
        }

        // 关闭当前进程句柄
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        ExitProcess(0);
    }
    return 0;
}


// 窗口过程回调函数
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	switch (uMsg) {
		// 处理窗口消息
		// ...
		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;
	}
	return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

DWORD WINAPI ProgramPicture_Thread(LPVOID lpParam) {
	std::string hIconFilePath = driveLetter + "\\Clever Eletrician\\Pic\\Program_main_pic.ico";
	
    // 创建一个控制台窗口
    HWND hwnd = GetConsoleWindow();
    LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE);
    style &= ~WS_THICKFRAME; // 移除调整窗口大小的样式
    SetWindowLongPtr(hwnd, GWL_STYLE, style); // 禁止调整窗口大小

    // 加载图标
    HICON hIcon = (HICON)LoadImage(NULL, hIconFilePath.c_str(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE);
 
	// 设置任务栏图标
	SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon); // 小图标
	SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);   // 大图标
 
	// 重绘窗口以使样式更改生效
	SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
	// 主循环
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
 
	// 释放图标资源
	DestroyIcon(hIcon);
	return 0;
}
 
struct ThreadData {
	int SetTimeShuthour,SetTimeShutminute;
};
 
bool ShutDown_ThreadMode = true;

DWORD WINAPI ShutDown_Thread(LPVOID lpParam) {
    // 转换参数类型并提取关机时间
    ThreadData* data = static_cast<ThreadData*>(lpParam);
    int TimeShuthour = data->SetTimeShuthour;
    int TimeShutminute = data->SetTimeShutminute;
    int WaitTime = std::stoi(UserSetFile("GET", "SlientRunTime")); // 读取用户设定的等待时间

    // 检查静默关机选项
    if (UserSetFile("GET", "ShutDown_Thread") == "T") { // 如果设置为静默关机，则执行
        bool CheckShutDown = false;

        while (ShutDown_ThreadMode) {
            // 获取本地时间
            time_t now = time(nullptr);
            struct tm* local_time = localtime(&now);
            int LocalTimehour = local_time->tm_hour;
            int LocalTimemin = local_time->tm_min;

            std::cout << "  | JMGJ: {" << TimeShuthour << ":" << TimeShutminute 
                      << "} " << LocalTimehour << ":" << LocalTimemin 
                      << " WT: " << WaitTime << "  | " << std::endl;

            // 如果当前时间接近设定的关机时间10分钟，取消原计划
            if (TimeShuthour == LocalTimehour && 
                TimeShutminute == LocalTimemin + 10 && 
                !CheckShutDown) {
                system("shutdown -a");
                CheckShutDown = true;
            }

            // 如果剩余时间小于等于等待时间，则发出关机指令
            if (TimeShuthour == LocalTimehour && 
                (TimeShutminute - LocalTimemin) <= WaitTime) {
                int secondsRemaining = (TimeShutminute - LocalTimemin) * 60;
                
                // 构造关机命令
                std::stringstream ss;
                ss << "shutdown -s -t " << secondsRemaining;
                std::string command = ss.str();
                system(command.c_str());

                // 线程退出
                return 0;
            }

            // 检查用户是否更改了等待时间
        	int newWaitTime = std::stoi(UserSetFile("GET", "SlientRunTime"));
            if (newWaitTime != WaitTime) {
                WaitTime = newWaitTime;
            }

            // 休眠1秒再检查
            Sleep(1000);
        }
    }

    // 释放数据对象内存，防止泄漏
    delete data;
    return 0;
}


DWORD WINAPI AutoColor_Thread(LPVOID lpParam) {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    bool isNightMode = false;
    std::string lastSetting = "F";
    
    // 创建一个事件对象用于精确计时
    HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);
    if (hTimer == NULL) return 1; // 创建失败，退出线程
    
    // 设置计时器为每秒触发一次
    LARGE_INTEGER liDueTime;
    liDueTime.QuadPart = -10000000; // -1秒（100纳秒为单位）
    SetWaitableTimer(hTimer, &liDueTime, 1000, NULL, NULL, FALSE);
    
    while (true) {
        // 等待计时器触发（每秒一次）
        WaitForSingleObject(hTimer, INFINITE);
        
        // 快速检查自动切换功能是否启用
        if (UserSetFile("GET", "AutoColor") != "T") {
            continue; // 未启用，跳过后续逻辑
        }
        
        // 获取当前时间（精确到秒）
        time_t now = time(nullptr);
        struct tm* local_time = localtime(&now);
        int currentHour = local_time->tm_hour;
        int currentMinute = local_time->tm_min;
        
        // 获取用户设置的时间范围
        std::string timeRange = UserSetFile("GET", "ColorChangeTime");
        size_t pos = timeRange.find('-');
        if (pos == std::string::npos) continue;
        
        try {
            int dayStartTime = std::stoi(timeRange.substr(0, pos));
            int dayEndTime = std::stoi(timeRange.substr(pos + 1));
            
            // 判断是否应该处于白天模式（根据用户设置的时间范围）
            bool shouldBeDayMode = (dayStartTime < dayEndTime)
                ? (currentHour >= dayStartTime && currentHour < dayEndTime)
                : (currentHour >= dayStartTime || currentHour < dayEndTime);
            
            // 根据白天/夜间模式决定实际颜色设置
            bool shouldBeNightMode = !shouldBeDayMode;
            std::string colorSetting = shouldBeNightMode ? "0F" : "F0";
            std::string modeName = shouldBeNightMode ? "夜间模式" : "白天模式";
            
            // 只有当模式需要改变且设置与上次不同时才执行切换
            if (shouldBeNightMode != isNightMode) {
                if (colorSetting != lastSetting) {
                    system(("color " + colorSetting).c_str());
                    lastSetting = colorSetting;
                    
                    // 添加调试输出（仅在颜色切换时输出）
                    std::cout << "\n[AutoColor] 时间切换: " 
                              << currentHour << ":" << std::setfill('0') << std::setw(2) << currentMinute 
                              << " (白天时段: " << dayStartTime << "-" << dayEndTime << ") -> " 
                              << modeName << std::endl;
                }
                
                isNightMode = shouldBeNightMode;
            }
            
            // 每秒输出当前时间和设置（用于调试）
            std::cout << "\r[AutoColor] 当前时间: " 
                      << currentHour << ":" << std::setfill('0') << std::setw(2) << currentMinute 
                      << " (白天时段: " << dayStartTime << "-" << dayEndTime << ") " 
                      << modeName 
                      << std::string(20, ' ') << std::flush;
            
        } catch (...) {
            continue; // 忽略解析错误，继续下一次检查
        }
    }
    
    CloseHandle(hTimer); // 关闭计时器句柄
    return 0;
}

struct SleepThreadData {
    int TimeSleepSec;
    int targetHour;
    int targetMinute;
    volatile bool terminate; // 终止标志
    int* weekdays;  // 用数组存储星期（C++98不支持vector在结构体中直接赋值）
	int weekdayCount; // 星期数量
};

// 线程函数（保持兼容）
DWORD WINAPI SleepDisplay_Thread(LPVOID lpParam) {
    SleepThreadData* data = (SleepThreadData*)lpParam; // 避免使用static_cast，兼容旧编译器
    int TimeSleepSec = data->TimeSleepSec;

    for (int i = 0; i < TimeSleepSec; ++i) {
    	cout<<"("<<TimeSleepSec<<")"<<endl;
        if (data->terminate) {
            // 释放星期数组内存
            if (data->weekdays != NULL) {
                delete[] data->weekdays;
            }
            delete data;
            return 0;
        }
        Sleep(1000);
    }

    // 执行睡眠操作
    SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
    SendMessage(FindWindow(NULL, NULL), WM_SYSCOMMAND, SC_MONITORPOWER, 2);

    // 释放内存
    if (data->weekdays != NULL) {
        delete[] data->weekdays;
    }
    delete data;
    return 0;
}

void Computer_Display_Sleep(const std::string& RunMode) {
    // 静态变量跟踪已创建的任务（C++98兼容，用平行数组替代tuple）
    static std::vector<int> scheduledHours;       // 已调度的小时
    static std::vector<int> scheduledMinutes;     // 已调度的分钟
    static std::vector<int*> scheduledWeekdays;   // 已调度的星期数组
    static std::vector<int> scheduledWeekCounts;  // 每个星期数组的长度
    static CRITICAL_SECTION cs;                   // 用Windows临界区替代mutex（C++98无std::mutex）
    static bool csInitialized = false;

    // 初始化临界区（只执行一次）
    if (!csInitialized) {
        InitializeCriticalSection(&cs);
        csInitialized = true;
    }

    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
    WORD defaultAttributes = consoleInfo.wAttributes;

    std::string DayDiaryFileF = driveLetter + "\\Clever Eletrician\\ProgramData\\DayDiary_file.Log";
    FILE* DayDiary_file = fopen(DayDiaryFileF.c_str(), "a");

    std::string timeFilePath = driveLetter + "\\Clever Eletrician\\ProgramData\\SleepDisplay.time";
    FILE* fin = fopen(timeFilePath.c_str(), "r");
    if (fin == NULL) {
        fprintf(DayDiary_file, "%s \n", "错误：用户无法打开时间文件，文件可能已经损坏或删除!");
        return;
    }
    fseek(fin, 0, SEEK_END);
    int Jiance = ftell(fin);
    fseek(fin, 0, SEEK_SET);
    
    if (Jiance == 0) {
        fprintf(DayDiary_file, "\n错误：无对应的字节数据! ");
        SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | (defaultAttributes & 0xF0));
        printf(" 无对应的字节数据\n");
        SetConsoleTextAttribute(hConsole, defaultAttributes);
        fclose(fin);
        return;
    }

    std::vector<int> hours;
    std::vector<int> minutes;
    std::vector<int*> weekdaysList;  // 存储每个任务的星期数组
    std::vector<int> weekdayCounts;  // 每个星期数组的长度
    int hour, minute, weekday;

    // 读取文件内容（兼容C++98的循环方式）
    while (fscanf(fin, "%d:%d[%d]", &hour, &minute, &weekday) != EOF) {
        if ((hour < 0 || hour > 23 || minute < 0 || minute > 59 || weekday < 0) && Jiance != 0) {
            printf(" 文件格式错误或数据超出范围，跳过当前行。\n");
            break;
        }
        hours.push_back(hour);
        minutes.push_back(minute);

        // 解析星期（用动态数组替代vector存储，兼容旧标准）
        int* weekArray = NULL;
        int count = 0;
        if (weekday == 0) {
            count = 7;
            weekArray = new int[7];
            for (int i = 0; i < 7; ++i) {
                weekArray[i] = i + 1; // 1-7
            }
        } else {
            // 计算数字位数
            int temp = weekday;
            while (temp > 0) {
                temp /= 10;
                count++;
            }
            // 存储星期
            weekArray = new int[count];
            temp = weekday;
            for (int i = count - 1; i >= 0; --i) {
                weekArray[i] = temp % 10;
                temp /= 10;
            }
        }
        weekdaysList.push_back(weekArray);
        weekdayCounts.push_back(count);
    }
    fclose(fin);

    // 获取当前时间
    time_t now;
    time(&now);
    struct tm* local_time = localtime(&now);
    int currentWeek = local_time->tm_wday == 0 ? 7 : local_time->tm_wday;
    int currentHour = local_time->tm_hour;
    int currentMinute = local_time->tm_min;
    int currentSec = local_time->tm_sec;

    // 存储待处理的任务
    std::vector<int> targetHours;
    std::vector<int> targetMinutes;
    std::vector<int*> targetWeekArrays;  // 星期数组
    std::vector<int> targetWeekCounts;   // 数组长度
    std::vector<int> sleepTimes;

    // 筛选有效任务（C++98风格循环）
    for (size_t i = 0; i < hours.size(); ++i) {
        if (i >= minutes.size() || i >= weekdaysList.size() || i >= weekdayCounts.size()) {
            continue; // 避免越界
        }

        int targetHour = hours[i];
        int targetMinute = minutes[i];
        int* weekArray = weekdaysList[i];
        int weekCount = weekdayCounts[i];

        // 检查当前星期是否匹配
        bool isValid = false;
        for (int j = 0; j < weekCount; ++j) {
            if (weekArray[j] == currentWeek) {
                isValid = true;
                break;
            }
        }
        if (!isValid) {
            continue;
        }

        // 计算睡眠时间
        int TimeSleepSec = (targetHour - currentHour) * 3600 + (targetMinute - currentMinute) * 60 - currentSec;
        if (TimeSleepSec <= 0) {
            TimeSleepSec += 24 * 3600; // 视为明天的任务
        }

        if (TimeSleepSec > 0) {
            targetHours.push_back(targetHour);
            targetMinutes.push_back(targetMinute);
            targetWeekArrays.push_back(weekArray);
            targetWeekCounts.push_back(weekCount);
            sleepTimes.push_back(TimeSleepSec);
        }
    }

    // 无任务处理
    if (sleepTimes.empty() && RunMode != "SilentRun") {
        SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | (defaultAttributes & 0xF0));
        printf(" 目前无睡眠任务\n");
        SetConsoleTextAttribute(hConsole, defaultAttributes);
        fprintf(DayDiary_file, "%s \n", "目前无睡眠任务，在此时间段内(中)");
        if (DayDiary_file) fclose(DayDiary_file);
        return;
    }

    // 创建线程前检查是否重复（C++98兼容）
    for (size_t i = 0; i < sleepTimes.size(); ++i) {
        int currHour = targetHours[i];
        int currMinute = targetMinutes[i];
        int* currWeeks = targetWeekArrays[i];
        int currWeekCount = targetWeekCounts[i];

        // 加锁检查是否已存在相同任务
        bool taskExists = false;
        EnterCriticalSection(&cs); // 替代lock_guard

        // 遍历已调度任务（C++98循环）
        for (size_t j = 0; j < scheduledHours.size(); ++j) {
            if (scheduledHours[j] != currHour || scheduledMinutes[j] != currMinute) {
                continue;
            }

            // 比较星期数组是否相同
            bool weeksEqual = true;
            if (scheduledWeekCounts[j] != currWeekCount) {
                weeksEqual = false;
            } else {
                for (int k = 0; k < currWeekCount; ++k) {
                    if (scheduledWeekdays[j][k] != currWeeks[k]) {
                        weeksEqual = false;
                        break;
                    }
                }
            }

            if (weeksEqual) {
                taskExists = true;
                break;
            }
        }

        LeaveCriticalSection(&cs);

        // 不重复则创建线程
        if (!taskExists) {
            SleepThreadData* data = new SleepThreadData;
            data->TimeSleepSec = sleepTimes[i];
            data->targetHour = currHour;
            data->targetMinute = currMinute;
            data->terminate = false;

            // 复制星期数组（避免指针失效）
            data->weekdayCount = currWeekCount;
            data->weekdays = new int[currWeekCount];
            for (int k = 0; k < currWeekCount; ++k) {
                data->weekdays[k] = currWeeks[k];
            }

            // 创建线程
            HANDLE hThread = CreateThread(NULL, 0, SleepDisplay_Thread, data, 0, NULL);
            if (hThread != NULL) {
                // 添加到已调度列表
                EnterCriticalSection(&cs);
                scheduledHours.push_back(currHour);
                scheduledMinutes.push_back(currMinute);
                // 复制星期数组到跟踪列表
                int* weekCopy = new int[currWeekCount];
                for (int k = 0; k < currWeekCount; ++k) {
                    weekCopy[k] = currWeeks[k];
                }
                scheduledWeekdays.push_back(weekCopy);
                scheduledWeekCounts.push_back(currWeekCount);
                LeaveCriticalSection(&cs);

                CloseHandle(hThread);
            } else {
                // 创建失败释放内存
                delete[] data->weekdays;
                delete data;
            }
        }
    }

    // 输出最近任务（兼容C++98）
    if (RunMode != "SilentRun" && !sleepTimes.empty()) {
        const char* days[] = {"", "周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        
        // 找到最小时间索引（C++98无std::min_element，手动实现）
        size_t nearestIndex = 0;
        int minSec = sleepTimes[0];
        for (size_t i = 1; i < sleepTimes.size(); ++i) {
            if (sleepTimes[i] < minSec) {
                minSec = sleepTimes[i];
                nearestIndex = i;
            }
        }

        // 输出信息
        printf(" 目标时间：%d时%d分", targetHours[nearestIndex], targetMinutes[nearestIndex]);
        
        // 输出星期
        int* weekArray = targetWeekArrays[nearestIndex];
        int weekCount = targetWeekCounts[nearestIndex];
        if (weekCount == 7) {
            printf(" 全周");
        } else {
            for (int j = 0; j < weekCount; ++j) {
                if (weekArray[j] >= 1 && weekArray[j] <= 7) {
                    printf(" %s", days[weekArray[j]]);
                }
            }
        }
        printf("\n   %d秒\n", sleepTimes[nearestIndex]);
    }

    if (DayDiary_file) fclose(DayDiary_file);
}

 
std::string encrypt(const std::string& str) {
    std::string result(str);
    for (size_t i = 0; i < result.length(); i++) {
        result[i] = (result[i] + 1) % 256;
    }
    return result;
}

std::string decrypt(const std::string& str) {
    std::string result(str);
    for (size_t i = 0; i < result.length(); i++) {
        result[i] = (result[i] - 1) % 256;
    }
    return result;
}

bool registerUser() {
    std::string username, password, confirmPassword;

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 清空输入缓冲区

    std::cout << " 请输入用户名：";
    std::cin >> username;

    std::cout << " 请输入密码：";
    password = "";
    char ch;
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (password.length() > 0) {
                password.pop_back();
                std::cout << "\b \b";
            }
        } else {
            password += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    std::cout << " 请确认密码：";
    confirmPassword = "";
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (confirmPassword.length() > 0) {
                confirmPassword.pop_back();
                std::cout << "\b \b";
            }
        } else {
            confirmPassword += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    if (password != confirmPassword) {
        std::cout << " 错误：两次输入的密码不一致。" << std::endl;
        return false;
    }
    std::string encryptedData = encrypt(username) + "," + encrypt(password);
    std::string result = UserSetFile("WRITE", "password", encryptedData);
    if (result == "SUCCESS") {
        std::cout << " 注册成功！" << std::endl;
        return true;
    }
    std::cout << " 注册失败！" << std::endl;
    return false;
}

bool login() {
    std::string username, password;
    std::cout << "\n 请输入用户名：";
    std::cin >> username;

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 清空输入缓冲区

    std::cout << " 请输入密码：";
    password = "";
    char ch;
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (password.length() > 0) {
                password.pop_back();
                std::cout << "\b \b";
            }
        } else {
            password += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    std::string encryptedData = UserSetFile("GET", "password");
    size_t pos = encryptedData.find(',');
    std::string encryptedUsername = encryptedData.substr(0, pos);
    std::string encryptedPassword = encryptedData.substr(pos + 1);
    if (decrypt(encryptedUsername) == username && decrypt(encryptedPassword) == password) {
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
        GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
        WORD defaultAttributes = consoleInfo.wAttributes;  // 获取默认的文本属性
        // 设置绿色文字，保留当前背景色
        SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | (defaultAttributes & 0xF0));
        std::cout << " 登录成功！" << std::endl;
        SetConsoleTextAttribute(hConsole, defaultAttributes);
        return true;
    }
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
    WORD defaultAttributes = consoleInfo.wAttributes;  // 获取默认的文本属性
    // 设置红色文字，保留当前背景色
    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
    std::cout << " 错误：登录失败，用户名或密码错误。" << std::endl;
    // 恢复默认颜色
    SetConsoleTextAttribute(hConsole, defaultAttributes);
    Sleep(1500);
    system("cls");
    return false;
}

bool changeUsername(std::string& username) {
    std::string newUsername, confirmUsername;
    std::cout << " 请输入新的用户名：";
    std::cin >> newUsername;
    std::cout << " 请确认新的用户名：";
    std::cin >> confirmUsername;
    if (newUsername != confirmUsername) {
        std::cout << " 错误：两次输入的用户名不一致。" << std::endl;
        return false;
    }
    std::string encryptedData = UserSetFile("GET", "password");
    size_t pos = encryptedData.find(',');
    std::string encryptedPassword = encryptedData.substr(pos + 1);
    std::string newEncryptedData = encrypt(newUsername) + "," + encryptedPassword;
    std::string result = UserSetFile("WRITE", "password", newEncryptedData);
    if (result == "SUCCESS") {
        username = newUsername;
        std::cout << " 修改用户名成功！" << std::endl;
        return true;
    }
    std::cout << " 错误：未找到该用户，请先注册。" << std::endl;
    return false;
}

bool changePassword(std::string& username) {
    std::string password, newPassword, confirmPassword;
    std::cout << " 请输入当前密码：";
    password = "";
    char ch;
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (password.length() > 0) {
                password.pop_back();
                std::cout << "\b \b";
            }
        } else {
            password += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    std::string encryptedData = UserSetFile("GET", "password");
    size_t pos = encryptedData.find(',');
    std::string encryptedUsername = encryptedData.substr(0, pos);
    std::string encryptedPassword = encryptedData.substr(pos + 1);
    if (decrypt(encryptedUsername) != username || decrypt(encryptedPassword) != password) {
        std::cout << " 错误：用户名或当前密码错误。" << std::endl;
        return false;
    }
    std::cout << " 请输入新密码：";
    newPassword = "";
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (newPassword.length() > 0) {
                newPassword.pop_back();
                std::cout << "\b \b";
            }
        } else {
            newPassword += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    std::cout << " 请确认新密码：";
    confirmPassword = "";
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (confirmPassword.length() > 0) {
                confirmPassword.pop_back();
                std::cout << "\b \b";
            }
        } else {
            confirmPassword += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    if (newPassword != confirmPassword) {
        std::cout << " 错误：两次输入的新密码不一致。" << std::endl;
        return false;
    }
    std::string newEncryptedData = encrypt(username) + "," + encrypt(newPassword);
    std::string result = UserSetFile("WRITE", "password", newEncryptedData);
    if (result == "SUCCESS") {
        std::cout << " 修改密码成功！" << std::endl;
        return true;
    }
    std::cout << " 错误：未找到该用户，请先注册。" << std::endl;
    return false;
}

bool changePassword() {
    std::string username, oldPassword, newPassword, confirmPassword;
    std::cout << " 请输入用户名：";
    std::cin >> username;
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 清空输入缓冲区
    std::cout << " 请输入旧密码：";
    oldPassword = "";
    char ch;
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (oldPassword.length() > 0) {
                oldPassword.pop_back();
                std::cout << "\b \b";
            }
        } else {
            oldPassword += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    std::string encryptedData = UserSetFile("GET", "password");
    size_t pos = encryptedData.find(',');
    std::string encryptedUsername = encryptedData.substr(0, pos);
    std::string encryptedPassword = encryptedData.substr(pos + 1);
    if (decrypt(encryptedUsername) != username || decrypt(encryptedPassword) != oldPassword) {
        std::cout << " 错误：用户名或旧密码错误。" << std::endl;
        return false;
    }
    std::cout << " 请输入新密码：";
    newPassword = "";
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (newPassword.length() > 0) {
                newPassword.pop_back();
                std::cout << "\b \b";
            }
        } else {
            newPassword += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    std::cout << " 请确认新密码：";
    confirmPassword = "";
    while ((ch = _getch()) != '\r') {
        if (ch == '\b') {
            if (confirmPassword.length() > 0) {
                confirmPassword.pop_back();
                std::cout << "\b \b";
            }
        } else {
            confirmPassword += ch;
            std::cout << '*';
        }
    }
    std::cout << std::endl;
    if (newPassword != confirmPassword) {
        std::cout << " 错误：两次输入的新密码不一致。" << std::endl;
        return false;
    }
    std::string newEncryptedData = encrypt(username) + "," + encrypt(newPassword);
    std::string result = UserSetFile("WRITE", "password", newEncryptedData);
    if (result == "SUCCESS") {
        std::cout << " 密码修改成功！" << std::endl;
        return true;
    }
    std::cout << " 密码修改失败！" << std::endl;
    return false;
}

bool checkFileExists() {
    std::string encryptedData = UserSetFile("GET", "password");
    if(encryptedData ==  ""){
		return false;
	}
    if (encryptedData.empty()) {
        std::cout << "\n ========请解锁========\n";
        return false;
    }
    return true;
}

 
std::string FindPath(const char* programName) {
      char path[MAX_PATH];
      if (SearchPath(NULL, programName, ".exe", MAX_PATH, path, NULL)) {
          return std::string(path);
      }
	  else if (SearchPath(NULL, programName, ".lnk", MAX_PATH, path, NULL)) {
	      return std::string(path);
	  }
      return std::string();
 }
 
void ComputerCrateFL(const std::string& CreateMode) {
	char user_name[MAX_PATH];
	DWORD size = MAX_PATH;
	GetUserNameA(user_name, &size);  // 获取当前用户名
	if(CreateMode == "CreateStartProgram"){
		std::string Programpath = FindPath(PROGRAM_FILENAME);
	    const char* source_path = Programpath.c_str(); // 源程序路径
	   
	    std::string startup_path = "C:\\Users\\";
	    startup_path += user_name;
	    startup_path += "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\";
	    startup_path += PROGRAM_FILENAME;
		
		// 1. 改用long long类型避免溢出（核心优化）
		long long result = 0, result2 = 0;  // 支持更大数值范围
		
		// 2. 解析ProgramVersion（复用统一逻辑）
		for (int i = 0; i < ProgramVersion.size(); ++i) {  // 用size()更安全，兼容std::string
		    char c = ProgramVersion[i];
		    char lowerC = tolower(c);  // 提前转小写，减少重复调用
		    
		    if (isdigit(c)) {
		        result = result * 10 + (c - '0');  // 数字转换
		    } else if (lowerC >= 'a' && lowerC <= 'z') {
		        result = result * 10 + (lowerC - 'a' + 1);  // 字母转换（a→1...z→26）
		    }
		    // 其他字符（标点、空格等）默认忽略，保持原逻辑
		}
		
		// 3. 解析FileVer（复用与上面完全一致的逻辑，减少重复）
		std::string FileVer = UserSetFile("GET", "ProgramVersion");
		for (int i = 0; i < FileVer.size(); ++i) {  // 用size()替代'\0'判断，更安全
		    char c = FileVer[i];
		    char lowerC = tolower(c);  // 统一处理逻辑，避免变量名混乱
		    
		    if (isdigit(c)) {
		        result2 = result2 * 10 + (c - '0');  // 与上面解析逻辑完全一致
		    } else if (lowerC >= 'a' && lowerC <= 'z') {
		        result2 = result2 * 10 + (lowerC - 'a' + 1);  // 保持逻辑统一
		    }
		    // 其他字符同样忽略，与ProgramVersion解析规则一致
		}
		
		// 4. 去掉重复输出（原代码打印了两次，保留一次即可）
		cout << "\n { ProgramVer:" << result2 << " FileProgramVer: " << result << "}";
		// 版本对比逻辑不变，保持原有判断
		if (result2 > result) {
		    printf("\n  【开机自启动设置失败】\n 错误：电教员程序版本过低，无高版本权限！");
		    return;
		}
	    else{
	    	std::string newVersion = ProgramVersion; // 替换为实际版本号
			UserSetFile("WRITE", "ProgramVersion", newVersion);
		}
	    
	    // 检查文件是否存在
	    std::ifstream file(startup_path);
	    if (file.good() && result2 == result) {
	        // 文件存在
			printf("\n  【开机自启动已曾设置】");
		    file.close();
		    return;
	    }
	    
	    // 打开源文件
	    FILE* source_file = fopen(source_path, "rb");
	    remove(startup_path.c_str());
	    if (!source_file) {
	       perror("\n  【开机自启动设置失败】\n 错误：文件添加时复制失败！");
	       return;
	    }
	
	   // 创建目标文件
	   FILE* destination_file = fopen(startup_path.c_str(), "wb");
	   if (!destination_file) {
	       fclose(source_file);
	       perror("\n  【开机自启动设置失败】\n 错误：程序在尝试创建目标文件时遇到问题");
	       return;
	   }
	   // 缓冲区大小（可以根据需要调整）
	   const size_t buffer_size = 4096;
	   char buffer[buffer_size];
	   size_t bytes_read;
	
	   // 复制文件内容
	   while ((bytes_read = fread(buffer, 1, buffer_size, source_file)) > 0) {
	       fwrite(buffer, 1, bytes_read, destination_file);
	   }
	
	   // 关闭文件
	   fclose(source_file);
	   fclose(destination_file);
	   printf("\n  【开机自启动设置成功】");
	}
	
	else if(CreateMode == "CreateProgramStartLnk"){
		std::string Programpath = FindPath(PROGRAM_FILENAME);
		if (Programpath.empty()) {
		    std::cerr << "Error: Program path is empty. Cannot create shortcut." << std::endl;
		    return;
		}
		
		// 在路径前后添加引号
		std::string formattedPath = "\"" + Programpath + "\"";
		// 替换单个斜杠 '\' 为双斜杠 '\\'
		size_t pos = 0;
		while ((pos = formattedPath.find('\\', pos)) != std::string::npos) {
		    formattedPath.replace(pos, 1, "\\\\");
		    pos += 2; // 跳过替换的两个字符
		}
		
		std::string fileName = PROGRAM_FILENAME; // 将宏定义的文件名转为字符串
	    size_t dotPos = fileName.find_last_of('.'); // 查找最后一个 '.' 的位置
	    std::string shortcutName;
	    if (dotPos != std::string::npos) {
	        shortcutName = fileName.substr(0, dotPos); // 截取从开头到 '.' 之前的部分
	    } else {
	        shortcutName = fileName; // 如果没有 '.'，直接使用整个文件名
	    }
		
		// 打印替换后的路径，仅测试用
		//std::cout << "Formatted Path: " << formattedPath << std::endl;
		
		//创建文件
		std::string ProgramStartLnkFileN = driveLetter + "\\Clever Eletrician\\ProgramData\\Create_shortcut.vbs";
		FILE *ProgramStartLnkFile = fopen(ProgramStartLnkFileN.c_str(), "w"); // 使用 c_str() 获取 C 风格字符串
		std::string vbsCode = 
	    "' 定义要创建快捷方式的目标路径\n"
	    "strTargetPath = \"" + Programpath +
		"\""
	    "\n"
	    "' 定义快捷方式的名称\n"
	    "strShortcutName = \""+ shortcutName + ".lnk\""
	    "\n"
	    "' 获取桌面路径\n"
	    "Set objShell = CreateObject(\"WScript.Shell\")\n"
	    "strDesktopPath = objShell.SpecialFolders(\"Desktop\")\n"
	    "strShortcutPath = strDesktopPath & \"\\\" & strShortcutName\n"
	    "\n"
	    "' 创建一个 WshShortcut 对象\n"
	    "Set objShortcut = objShell.CreateShortcut(strShortcutPath)\n"
	    "\n"
	    "' 设置快捷方式的属性\n"
	    "objShortcut.TargetPath = strTargetPath\n"
	    "objShortcut.WindowStyle = 1 ' 默认为正常窗口\n"
	    "objShortcut.IconLocation = strTargetPath ' 也可以指定一个不同的图标文件，例如：\"C:\\Path\\To\\Icon.ico\"\n"
	    "\n"
	    "' 保存快捷方式\n"
	    "objShortcut.Save\n"
	    "\n"
	    "' 清理\n"
	    "Set objShortcut = Nothing\n"
	    "Set objShell = Nothing\n"
	    "\n";
	    std::string vbsCodeMessage = "' 消息框提示快捷方式已创建\n"
	    "WScript.Echo \"快捷方式已创建在桌面上：\" & strShortcutPath\n";
		
		fprintf(ProgramStartLnkFile, "%s", vbsCode.c_str());
		// 关闭文件
		fclose(ProgramStartLnkFile);
		
		const char* vbsFilePath = ProgramStartLnkFileN.c_str(); // 替换为你的.vbs文件路径
		// 使用ShellExecute运行VBScript
		HINSTANCE RunVBScript = ShellExecute(nullptr, "open", vbsFilePath, nullptr, nullptr, SW_SHOWNORMAL);	
	}
	
	else if(CreateMode == "DeleteProgramStartLnk"){
		std::string fileName = PROGRAM_FILENAME; // 将宏定义的文件名转为字符串
	    size_t dotPos = fileName.find_last_of('.'); // 查找最后一个 '.' 的位置
	    std::string shortcutName;
	    if (dotPos != std::string::npos) {
	        shortcutName = fileName.substr(0, dotPos); // 截取从开头到 '.' 之前的部分
	    } else {
	        shortcutName = fileName; // 如果没有 '.'，直接使用整个文件名
	    }
	    
		// 设置文件路径
		std::string ProgramStartLnkFileN = driveLetter + "\\Clever Eletrician\\ProgramData\\Create_shortcut.vbs";
		std::string ProgramStartLnk = "C:\\Users\\";
		ProgramStartLnk += user_name;
		ProgramStartLnk += "\\Desktop\\" + shortcutName + ".lnk";
		
	    // 删除文件
	    if (DeleteFileA(ProgramStartLnk.c_str()) && DeleteFileA(ProgramStartLnkFileN.c_str())) {
	        std::cout << "快捷方式删除成功: " << ProgramStartLnk << std::endl;
	    } else {
	        std::cerr << "快捷方式失败! 错误代码: " << GetLastError() << std::endl;
	    }
	
	}
	
	else {
	    std::cout << "无效的创建模式: " << CreateMode << std::endl;
	}
   
}

void ComputerProgramUserInput(const std::string& mode) { // mode: "Shutdown"/"Reboot"/"Sleep"
    system("cls");
    
    // 1. 初始化日志与文件路径
    std::string DayDiaryFileF = driveLetter + "\\Clever Eletrician\\ProgramData\\DayDiary_file.Log";
    FILE* DayDiary_file = fopen(DayDiaryFileF.c_str(), "a");
    fprintf(DayDiary_file, "%s \n", "用户输入并设置时间：");

    std::string filePath;
    std::string operationName; // 操作名称（关机/重启/睡眠）
    if (mode == "Shutdown") {
        filePath = driveLetter + "\\Clever Eletrician\\ProgramData\\SetShutdown.time";
        operationName = "定时关机";
    } else if (mode == "Reboot") {
        filePath = driveLetter + "\\Clever Eletrician\\ProgramData\\SetReboot.time";
        operationName = "定时重启";
    } else {
        filePath = driveLetter + "\\Clever Eletrician\\ProgramData\\SleepDisplay.time";
        operationName = "定时睡眠";
    }

    // 2. 检查文件是否已有数据，确定操作模式（覆盖/追加）
    bool isAppend = false;
    FILE* file = fopen(filePath.c_str(), "a"); // 先以追加模式打开检查大小
    if (!file) {
        printf(" 错误：无法打开文件！\n");
        fclose(DayDiary_file);
        return;
    }

    fseek(file, 0, SEEK_END);
    int fileSize = ftell(file);
    fclose(file);

    if (fileSize > 0) { // 已有数据，提示用户选择
        printf("\n ===========数据提示===========");
        printf("\n 检测到的总字节大小：%d", fileSize);
        printf("\n 已存放数据文件! 小心覆盖！！！\n");
        printf(" 请关闭文本编辑器以确保数据正确写入\n");
        printf("\n 需要覆盖还是追加？【1 覆盖 2 追加 任意键 退出】\n");
        printf(" 请输入：");
        
        int choice;
        cin >> choice;
        if (choice == 1) {
            // 覆盖模式：以"w"打开（清空文件）
            file = fopen(filePath.c_str(), "w");
        } else if (choice == 2) {
            // 追加模式：以"a"打开（保留原有内容）
            isAppend = true;
            file = fopen(filePath.c_str(), "a");
        } else {
            // 退出操作
            fclose(DayDiary_file);
            return;
        }
    } else {
        // 无数据，直接以"w"模式创建/打开
        file = fopen(filePath.c_str(), "w");
    }

    // 再次检查文件打开状态
    if (!file) {
        printf(" 错误：文件打开失败！\n");
        fclose(DayDiary_file);
        return;
    }

    // 3. 提示用户输入时间配置
    std::string actionDesc = isAppend ? "追加" : "设置";
    system("cls");
    printf("\n ===========%s%s===========", actionDesc.c_str(), operationName.c_str());
    printf("\n 请输入此电脑%s时间段数量：(0-5)\n", operationName.c_str());
    printf(" 输入格式：小时 分钟 星期\n");
    printf(" 星期段输入0为每天执行任务\n 请输入：");

    int timeCount;
    scanf("%d", &timeCount);

    // 存储用户输入的时间数据
    std::vector<int> hours(timeCount);
    std::vector<int> minutes(timeCount);
    std::vector<int> weekdays(timeCount);

    // 4. 循环读取并验证时间数据
    for (int i = 0; i < timeCount; i++) {
        printf("\n 请输入第%d个时间\n", i + 1);
        scanf("%d %d %d", &hours[i], &minutes[i], &weekdays[i]);

        // 输入合法性验证
        if (hours[i] < 0 || hours[i] > 23 || minutes[i] < 0 || minutes[i] > 59 || weekdays[i] < 0 || weekdays[i] > 7777777) {
            printf(" 数据错误（小时0-23，分钟0-59，星期0-7），请重新输入！\n");
            i--; // 重新输入当前项
            continue;
        }

        // 显示用户输入的时间信息
        printf(" 设定第%d个时间为：%d时%d分 ", i + 1, hours[i], minutes[i]);
        if (weekdays[i] == 0) {
            printf("全周 ");
        } else {
            // 解析星期数字（如135→周一三五）
            int wd = weekdays[i];
            int len = 1;
            while (wd / len > 7) len *= 10; // 计算位数
            
            while (wd > 0) {
                int day = wd / len;
                switch (day) {
                    case 1: printf("周一 "); break;
                    case 2: printf("周二 "); break;
                    case 3: printf("周三 "); break;
                    case 4: printf("周四 "); break;
                    case 5: printf("周五 "); break;
                    case 6: printf("周六 "); break;
                    case 7: printf("周日 "); break;
                    default: printf("无效 "); break;
                }
                wd %= len;
                len /= 10;
            }
        }
        printf("\n");

        // 写入文件（格式：小时:分钟[星期]）
        fprintf(file, "%d:%d[%d]\n", hours[i], minutes[i], weekdays[i]);
    }

    // 5. 收尾工作
    fclose(file);
    fclose(DayDiary_file);

    // 提示完成信息
    printf("\n %s电脑%s结束\n", actionDesc.c_str(), operationName.c_str());
    
    // 关机模式特殊处理（重置线程状态）
    if (mode == "Shutdown") {
        OnlyRunShutThread = 0;
        ShutDown_ThreadMode = false;
    }

    Sleep(2000);
}

int Computer_Power_Off(const std::string& RunMode, bool Stepout, bool ScilentSut) {
    // 1. 区分模式：确定读取的文件
    const bool isRebootMode = (RunMode == "Reboot");
    const std::string timeFileName = isRebootMode ? "SetReboot.time" : "SetShutdown.time";
    const std::string taskType = isRebootMode ? "重启" : "关机";

    // 控制台颜色与日志文件初始化（不变）
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
    const WORD defaultAttributes = consoleInfo.wAttributes;
    const std::string DayDiaryFileF = driveLetter + "\\Clever Eletrician\\ProgramData\\DayDiary_file.Log";
    FILE* DayDiary_file = fopen(DayDiaryFileF.c_str(), "a");
    if (!DayDiary_file) return 0;

    // 2. 读取对应模式的时间配置文件（不变）
    const std::string filePath = driveLetter + "\\Clever Eletrician\\ProgramData\\" + timeFileName;
    FILE* fin = fopen(filePath.c_str(), "r");
    if (!fin) {
        fprintf(DayDiary_file, "%s \n", ("错误：无法打开" + timeFileName + "，文件可能损坏或删除!").c_str());
        SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | (defaultAttributes & 0xF0));
        printf(" 无对应的文件 %s\n", timeFileName.c_str());
        SetConsoleTextAttribute(hConsole, defaultAttributes);
        fclose(DayDiary_file);
        return 0;
    }

    // 统计文件行数（不变）
    fseek(fin, 0, SEEK_END);
    const int fileSize = ftell(fin);
    rewind(fin);
    int line = 0;
    char c, lastC = 0;
    while ((c = fgetc(fin)) != EOF) {
        if (c == '\n') line++;
        lastC = c;
    }
    if (lastC != '\n') line++;
    rewind(fin);

    // 非静默模式下检查文件空（不变）
    if (RunMode != "SilentRun" && fileSize == 0) {
        fprintf(DayDiary_file, "\n错误：%s无对应的字节数据! ", timeFileName.c_str());
        SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | (defaultAttributes & 0xF0));
        printf(" 无对应的字节数据\n");
        SetConsoleTextAttribute(hConsole, defaultAttributes);
        fclose(fin);
        fclose(DayDiary_file);
        return 0;
    }

    // 3. 读取时间配置到优先级队列（核心修改：使用最小堆，按时间从早到晚排序）
    // 定义比较器：让priority_queue成为最小堆（早的时间优先）
    auto cmp = [](const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) {
        // 先比较小时，小时小的优先
        if (a.second.first != b.second.first) {
            return a.second.first > b.second.first; // 小时小的排在前
        }
        // 小时相同则比较分钟，分钟小的优先
        return a.second.second > b.second.second;
    };
    // 使用最小堆替代默认的最大堆
    priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, decltype(cmp)> taskQueue(cmp);

    int allday = 1; // 1=非全周，0=全周
    for (int i = 0; i < line; ++i) {
        int hour, min, week;
        if (fscanf(fin, "%d:%d[%d]", &hour, &min, &week) != 3) {
            fprintf(DayDiary_file, "%s \n", ("错误：读取" + timeFileName + "内容失败，数据格式不匹配!").c_str());
            printf(" %s格式错误或数据不完整\n", timeFileName.c_str());
            fclose(fin);
            fclose(DayDiary_file);
            return 0;
        }
        // 调试：打印读取到的原始任务
        //printf(" 调试：读取到任务 - 时间：%d:%d，星期配置：%d\n", hour, min, week);

        // 全周任务处理（不变）
        if (week == 0) {
            allday = 0;
            for (int j = 1; j <= 7; j++) {
                taskQueue.emplace(j, make_pair(hour, min));
            }
        } else {
            // 解析多星期（如135=周一三五）
            while (week != 0) {
                taskQueue.emplace(week % 10, make_pair(hour, min));
                week /= 10;
            }
        }
    }
    fclose(fin);

    // 获取当前时间（不变）
    time_t now = time(nullptr);
    tm* localTime = localtime(&now);
    tm currentTime = *localTime;
    const int currHour = currentTime.tm_hour;
    const int currMin = currentTime.tm_min;
    const int currSec = currentTime.tm_sec;
    const int currWeek = currentTime.tm_wday ? currentTime.tm_wday : 7; // tm_wday=0是周日
    //printf(" 调试：当前时间 - 星期：%d，时间：%d:%d:%d\n", currWeek, currHour, currMin, currSec);

    // 4. 筛选有效任务：因使用最小堆，首个有效任务就是最早的时间
    bool hasValidTask = false;
    pair<int, int> targetTime; // 目标重启/关机时间
    while (!taskQueue.empty()) {
        auto [taskWeek, taskTime] = taskQueue.top();
        taskQueue.pop();

        // 调试：打印当前处理的任务
        //printf(" 调试：检查任务 - 星期：%d，时间：%d:%d\n", taskWeek, taskTime.first, taskTime.second);

        if (taskWeek != currWeek) continue; // 只处理当前星期的任务

        // 判断任务时间是否在当前时间之后
        bool isAfter = false;
        if (taskTime.first > currHour) {
            isAfter = true;
        } else if (taskTime.first == currHour && taskTime.second > currMin) {
            isAfter = true;
        } else if (taskTime.first == currHour && taskTime.second == currMin && currSec == 0) {
            isAfter = true; // 刚好在整分钟，视为有效
        }

        if (isAfter) {
            targetTime = taskTime;
            hasValidTask = true;
            printf(" 调试：找到有效任务 - 时间：%d:%d\n", targetTime.first, targetTime.second);
            break; // 最小堆保证首个有效任务是最早的，直接退出
        }
    }

    // 5. 非Reboot模式处理Stepout（不变）
    if (!isRebootMode && hasValidTask) {
        int validTaskCnt = 1;
        while (!taskQueue.empty()) {
            auto [taskWeek, taskTime] = taskQueue.top();
            taskQueue.pop();

            if (taskWeek != currWeek) continue;
            if (currHour < taskTime.first || (currHour == taskTime.first && currMin < taskTime.second)) {
                validTaskCnt++;
                if (Stepout) continue;
                if (validTaskCnt > 1 && (taskTime.first < targetTime.first || 
                    (taskTime.first == targetTime.first && taskTime.second < targetTime.second))) {
                    targetTime = taskTime;
                }
            }
        }
        if (Stepout && validTaskCnt == 1) {
            hasValidTask = false;
        }
    }

    // 6. 非静默模式：任务有效性提示（不变）
    if (RunMode != "SilentRun") {
        if (!hasValidTask || Stepout == true) {
            SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | (defaultAttributes & 0xF0));
            printf("  目前无%s任务\n", taskType.c_str());
            SetConsoleTextAttribute(hConsole, defaultAttributes);
            fprintf(DayDiary_file, "目前无%s任务，在此时间段内（中）\n", taskType.c_str());
            fclose(DayDiary_file);
            return 0;
        }
        if (targetTime.first > 23 || targetTime.second > 59) {
            SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | (defaultAttributes & 0xF0));
            printf("  输入数据错误，请重新设置\n");
            SetConsoleTextAttribute(hConsole, defaultAttributes);
            fclose(DayDiary_file);
            return 0;
        }
    }

    // 7. 计算剩余时间（优化跨天处理）
    const int targetSec = targetTime.first * 3600 + targetTime.second * 60;
    const int currTotalSec = currHour * 3600 + currMin * 60 + currSec;
    int remainingSec = targetSec - currTotalSec;
    if (remainingSec < 0) {
        remainingSec += 24 * 3600; // 跨天处理（加24小时）
        printf(" 调试：任务跨天，剩余时间（秒）：%d\n", remainingSec);
    } else {
        printf(" 调试：剩余时间（秒）：%d\n", remainingSec);
    }

    // 8. 执行重启/关机命令（不变）
    if (!ShutFirst || isRebootMode) {
        system("shutdown -a > nul 2>&1");
        const string cmdParam = isRebootMode ? "-r" : "-s";
        const string cmd = "shutdown " + cmdParam + " -t " + to_string(remainingSec);
        cout << (isRebootMode ? "Reboot" : "Shutdown") << " command: " << cmd << "\n";
        system(cmd.c_str());
        ShutFirst = true;
    }

    // 9. 非Reboot模式处理ScilentSut线程（不变）
    if (!isRebootMode && ScilentSut && !ShutDown_ThreadMode) {
        const int silentMin = std::stoi(UserSetFile("GET", "SlientRunTime"));
        if (remainingSec > silentMin * 60 && OnlyRunShutThread == 0) {
            ShutDown_ThreadMode = true;
            cout << "Shutthread is running...\n";
            ThreadData* threadData = new ThreadData{targetTime.first, targetTime.second};
            HANDLE hThread = CreateThread(nullptr, 0, ShutDown_Thread, threadData, 0, nullptr);
            if (hThread != nullptr) {
                CloseHandle(hThread);
                OnlyRunShutThread++;
            } else {
                delete threadData;
            }
        }
    }

    // 10. 非静默模式：输出结果（不变）
    if (RunMode != "SilentRun") {
        cout << "  目标时间:";
        if (allday == 0) {
            cout << "全周 ";
        } else {
            const char* weekNames[] = {"", "周一", "周二", "周三", "周四", "周五", "周六", "周天"};
            cout << weekNames[currWeek] << " ";
        }
        cout << targetTime.first << "时" << targetTime.second << "分\n";
        fprintf(DayDiary_file, "目标%s时间：%d 时 %d 分\n", taskType.c_str(), targetTime.first, targetTime.second);
        
        const int remainingMin = remainingSec / 60;
        const int remainingHour = remainingMin / 60;
        const int remainingMinMod = remainingMin % 60;
        if (remainingHour > 0) {
            cout << "  将在" << remainingHour << "小时" << remainingMinMod << "分钟后" << taskType;
        } else {
            cout << "  将在" << remainingMinMod << "分钟后" << taskType;
        }
    }

    fclose(DayDiary_file);
    return 0;
}
 
bool hEvent = true;
 
DWORD WINAPI ResetShottime_Thread(LPVOID) {
    // 检查用户设置
    int WhitTime = std::stoi(UserSetFile("GET", "ResetShotTime"));
    if (UserSetFile("GET","SlientRun") == "T" && UserSetFile("GET","SHOUTDOWN") == "T") {//4 2
        // 日期检查初始化
        time_t now;  // 定义一个time_t类型的变量now来存储当前的时间
        struct tm* local_time;
        int OldDay;

        // 获取初始日期
        time(&now);  // 获取当前的时间，并将其存储在变量now中
        local_time = localtime(&now);  // 将当前时间转换为本地时间，并将其存储在一个struct tm指针变量local_time中
        OldDay = local_time->tm_yday;  // 从local_time中提取一年中的第几天

        while (hEvent) {
            // 每次循环时获取当前系统时间
            time(&now);  // 获取当前的时间
            local_time = localtime(&now);  // 将当前时间转换为本地时间
            int LocalDay = local_time->tm_yday;  // 从local_time中提取一年中的第几天

            // 检查是否是新的一天
            if (LocalDay > OldDay) {
                // 更新记录的日期
                // 执行任务
                cout<<" Taking Tasks:  ";
                Sleep(1000);
                ShutFirst = true; // ...
                Computer_Power_Off("SilentRun", false, false);
                Computer_Display_Sleep("SilentRun");
                OldDay = LocalDay;
            }
            // 输出调试信息
            std::cout << " { old " << OldDay << " | new " << LocalDay << " }" << std::endl;
            // 读取文件，值为任意正整数
            int SleepWhitTime = 0;
            while(SleepWhitTime < std::stoi(UserSetFile("GET", "ResetShotTime")) + 1){
				if(UserSetFile("GET","SlientRun") == "F"){
					return 0;
				}
				if(WhitTime != std::stoi(UserSetFile("GET", "ResetShotTime"))){
					WhitTime = std::stoi(UserSetFile("GET", "ResetShotTime"));
				}
				Sleep(1000);
				SleepWhitTime++;
			}
        }
    }
    return 0;
}

DWORD WINAPI RefreshDisplay(LPVOID lpParam) {
    while (true) {
        // 获取控制台窗口信息
        CONSOLE_SCREEN_BUFFER_INFO screenInfo;
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        GetConsoleScreenBufferInfo(hConsole, &screenInfo);
 
        // 清空显示区域的字符和颜色属性
        COORD position = {0, 0};  // 将位置向下移动一行
        DWORD charsWritten;
        FillConsoleOutputCharacter(hConsole, ' ', screenInfo.dwSize.X * 1, position, &charsWritten);
        FillConsoleOutputAttribute(hConsole, screenInfo.wAttributes, screenInfo.dwSize.X * 1, position, &charsWritten);
 
        // 输出时间
        SYSTEMTIME st;
        GetLocalTime(&st);
        char buffer[80];
        sprintf(buffer, "    %04d/%02d/%02d %02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
        WriteConsoleOutputCharacter(hConsole, buffer, strlen(buffer), position, &charsWritten);
 
        // 可以根据需要进行适当的延迟
        Sleep(10);
    }
}

int main(int argc, char *argv[]) {
	long long UserInput, UserInput2, tot, ProgramAuto, Jiance;
	UserInput = UserInput2 = tot = ProgramAuto = Jiance = 0;
	
	/*
		HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
	    DWORD prev_mode;
	    GetConsoleMode(hInput, &prev_mode); 
	    SetConsoleMode(hInput, prev_mode & ~ENABLE_QUICK_EDIT_MODE); //禁用QuickEdit模式
	*/
	
	char Programtitle[20] = "title 聪明的电教员"; // 设置cmd窗口标题为 “聪明的电教员”
	system(" mode con cols=90 lines=30"); // 窗口宽度高度
	system((Programtitle + ProgramVersion).c_str());
	
	HANDLE hMutex = CreateMutex(NULL, TRUE, "Clever Eletrician");
	if (GetLastError() == ERROR_ALREADY_EXISTS) {
	    // 释放互斥体句柄
	    if (hMutex != NULL) {
	        CloseHandle(hMutex);
	    }
	    GetLastError(); // 获取错误码
	    MessageBox(NULL, "聪明的电教员程序已经在运行中", "程序重复启动", MB_OK | MB_ICONINFORMATION);
        return 0;
	}
	
    // 存储扫描到的Clever Eletrician文件夹所在盘符
	std::vector<std::string> foundDrives;
	// 错误码及上下文变量
	std::string errCode = "";
	std::string scanDrive = "";
	std::string configDrive = "";
	std::string commonConfigDrive = "";
	std::string copyErrInfo = "";
	std::string deleteOldErrInfo = "";
	bool needInit = false;
	
	// 第一阶段：扫描所有盘符中的Clever Eletrician文件夹
	for (char drive = 'C'; drive <= 'Z'; ++drive) {
	    std::string checkPath = std::string(1, drive) + ":\\Clever Eletrician";
	    if (_access(checkPath.c_str(), 0) != -1) {
	        foundDrives.push_back(std::string(1, drive) + ":");
	    }
	}
	// 错误码1：未扫描到任何目标文件夹
	if (foundDrives.empty()) {
	    needInit = true; // 触发初始化流程
	}
	
	// 当前程序路径处理
		char current_program_path[256];
		snprintf(current_program_path, sizeof(current_program_path), "%s", "聪明的电教员.exe");
	
	// 检查文件是否存在及重命名逻辑
		std::ifstream file(FindPath(PROGRAM_FILENAME));
		if (strcmp(current_program_path, PROGRAM_FILENAME) == 0 || file.good()) {
		    printf(" 新文件名与当前文件名相同，跳过复制重命名操作。\n");
		} else {
		    char* current_exe_path = argv[0]; // 当前程序完整路径
		    char copy_command[256];
		    snprintf(copy_command, sizeof(copy_command), "copy %s %s", current_exe_path, PROGRAM_FILENAME);
		    
		    if (system(copy_command) == 0 && !file.good()) {
		        printf(" 成功复制重命名程序到新文件：%s\n", PROGRAM_FILENAME);
		        char delete_command[256];
		        snprintf(delete_command, sizeof(delete_command), "del %s", current_exe_path);
		        
		        if (system(delete_command) == 0) {
		            printf("成功删除旧的程序文件：%s\n", current_exe_path);
		        } else {
		            perror("删除旧程序文件失败");
		        }
		    } else {
		        perror("复制重命名程序失败");
		    }
		}
	
	// 第二阶段：盘符配置检测（设置错误码）
	std::string driveLetter;
	if (errCode.empty() && !foundDrives.empty()) {
	    if (foundDrives.size() == 1) {
	        scanDrive = foundDrives[0];
	        std::string settingFile = scanDrive + "\\Clever Eletrician\\ProgramData\\UserSetting.Set";
	        FILE* f = fopen(settingFile.c_str(), "r");
	        
	        if (f) {
	            fclose(f);
	            configDrive = UserSetFile("GET", "Driveletter");
	            bool configExists = false;
	            if (!configDrive.empty()) {
	                DWORD driveType = GetDriveTypeA(configDrive.c_str());
	                configExists = (driveType != DRIVE_NO_ROOT_DIR);
	            }
	            if (!configExists) {
	                errCode = "SINGLE_CONFIG_DRIVE_INVALID"; // 错误码4：单盘符配置无效
	            } else {
	                driveLetter = configDrive;
	            }
	        } else {
	            driveLetter = scanDrive; // 无配置文件，直接使用扫描到的盘符
	        }
	    } else {
	        std::vector<std::string> configDrives;
	        for (const auto& drive : foundDrives) {
	            std::string settingFile = drive + "\\Clever Eletrician\\ProgramData\\UserSetting.Set";
	            FILE* f = fopen(settingFile.c_str(), "r");
	            if (f) {
	                fclose(f);
	                std::string cfg = UserSetFile("GET", "Driveletter");
	                if (!cfg.empty()) configDrives.push_back(cfg);
	            }
	        }
	
	        bool allSame = true;
	        if (!configDrives.empty()) {
	            commonConfigDrive = configDrives[0];
	            for (const auto& d : configDrives) {
	                if (d != commonConfigDrive) {
	                    allSame = false;
	                    break;
	                }
	            }
	        }
	
	        if (allSame && !configDrives.empty()) {
	            DWORD driveType = GetDriveTypeA(commonConfigDrive.c_str());
	            if (driveType == DRIVE_NO_ROOT_DIR) {
	                errCode = "MULTI_CONFIG_DRIVE_INVALID"; // 错误码5：多盘符共同配置无效
	            } else {
	                driveLetter = commonConfigDrive;
	            }
	        } else if (!configDrives.empty() && !allSame) {
	            errCode = "MULTI_CONFIG_CONFLICT"; // 错误码6：多盘符配置冲突
	        } else {
	            driveLetter = foundDrives[0]; // 无配置，默认第一个盘符
	        }
	    }
	}
	
	// 检查删除标记文件（修改后：一次性删除所有带删除文件的盘符）
	if (errCode.empty()) {
	    std::vector<std::string> deletedDrives; // 记录所有已删除的盘符，用于最终提示
	    for (const auto& drive : foundDrives) {
	        // 构建删除标记文件路径（drive已带冒号，如"C:"）
	        std::string deleteFilePath = drive + "\\Clever Eletrician\\ProgramData\\DeleteProgramFile.sh";
	        FILE* deleteFilePtr = fopen(deleteFilePath.c_str(), "r");
	        
	        if (deleteFilePtr != NULL) {
	            fclose(deleteFilePtr); // 先关闭文件句柄，避免占用
	            
	            // 执行删除命令：删除当前盘符下的整个Clever Eletrician文件夹
	            std::string deleteCommand = "rmdir /s /q \"" + drive + "\\Clever Eletrician\"";
	            int deleteRet = system(deleteCommand.c_str()); // 记录命令执行结果
	            
	            // 若删除成功，添加到已删除列表
	            if (deleteRet == 0) {
	                deletedDrives.push_back(drive);
	            } else {
	                // 可选：提示单个盘符删除失败（按需保留）
	                printf(" 警告：%s 盘删除失败（可能权限不足）\n", drive.c_str());
	            }
	        }
	        // 容错：确保文件句柄关闭（即使文件不存在）
	        if (deleteFilePtr != NULL) {
	            fclose(deleteFilePtr);
	        }
	    }
	    
	    // 所有盘符检查完毕后，统一提示删除结果
	    if (!deletedDrives.empty()) {
	        system("cls");
	        printf(" ===================================\n");
	        printf(" 已成功删除以下盘符的程序文件：\n");
	        // 遍历输出所有已删除的盘符
	        for (const auto& delDrive : deletedDrives) {
	            printf(" %s 盘中的\"Clever Eletrician\"文件夹\n", delDrive.c_str());
	        }
	        printf(" ===================================\n");
	        Sleep(2000); // 延长提示时间，让用户看清结果
	        exit(0); // 所有删除完成后再退出
	    }
	}
	
	// 统一错误处理模块
	if (!errCode.empty()) {
	    system("cls");
	    printf(" ============程序错误恢复===========\n");
	    printf(" 程序检测到异常：\n");
		printf(" 一些错误的操作导致了程序配置文件出错\n");
	    if (errCode == "SINGLE_CONFIG_DRIVE_INVALID") {
	        printf(" 原因：配置的盘符不存在（%s）\n", configDrive.empty() ? "未设置" : configDrive.c_str());
	        printf(" ===================================\n");
	        printf(" 是否使用扫描到的盘符：%s【Y（确定） 任意键（退出）】？\n", scanDrive.c_str());
	        printf(" 请输入：");
	        char choice;
	        std::cin >> choice;
	        if (choice == 'Y' || choice == 'y') {
	            driveLetter = scanDrive;
	            UserSetFile("WRITE", "Driveletter", driveLetter);
	            printf(" 已更新盘符为：%s\n", driveLetter.c_str());
	        } else {
	            printf(" 退出程序\n");
	            Sleep(500);
	            exit(0);
	        }
	    } else if (errCode == "MULTI_CONFIG_CONFLICT") {
	        printf(" 原因：多程序文件夹配置不一致\n");
	        printf(" 请选择以下存在的盘符：\n");
	        for (size_t i = 0; i < foundDrives.size(); ++i) {
	            printf(" %d. %s 盘\n", i+1, foundDrives[i].c_str());
	        }
	        printf(" ===================================\n");
	        printf(" 请输入：");
	        int choice;
	        std::cin >> choice;
	        if (choice >= 1 && choice <= (int)foundDrives.size()) {
	            driveLetter = foundDrives[choice-1];
	            UserSetFile("WRITE", "Driveletter", driveLetter);
	            printf(" 已选择盘符：%s\n", driveLetter.c_str());
	        } else {
	            printf(" 输入无效，退出程序\n");
	            Sleep(500);
	            exit(0);
	        }
	    } else if (errCode == "MULTI_CONFIG_DRIVE_INVALID") {
	        printf(" 原因：共同配置的盘符不存在（%s）\n", commonConfigDrive.c_str());
	        printf(" ===================================\n");
	        printf(" 是否使用扫描到的第一个盘符：%s？【Y（确定） 任意键（退出）】\n", foundDrives[0].c_str());
	        printf(" 请输入：");
	        char choice;
	        std::cin >> choice;
	        if (choice == 'Y' || choice == 'y') {
	            driveLetter = foundDrives[0];
	            UserSetFile("WRITE", "Driveletter", driveLetter);
	            printf(" 已更新盘符为：%s\n", driveLetter.c_str());
	        } else {
	            printf(" 退出程序\n");
	            Sleep(500);
	            exit(0);
	        }
	    }
	    Sleep(1000);
	    system("cls");
	}
	
	// 初始化处理（未扫描到任何文件夹时）
	if (needInit) {
	    printf("\n ===================================\n");
	    printf(" 欢迎您首次使用“聪明的电教员”程序！\n");
	    printf(" 请您使用键盘上的数字进行输入，谢谢！\n");
	    printf(" 否则，可能会导致程序直接退出。\n");
	    printf(" 输入零键用以退出程序内部功能\n");
	    printf(" ===================================\n");
	    printf("\n 使用聪明的电教员，需要申请以下权限：\n");
	    printf("\n 1.读写/删除/访问存储设备\n 2.读取本地系统时间 \n 3.访问文件管理器，将程序设定为开机自\n   启动程序 \n 你同意吗？【Y （确定） 任意键 （退出）】");
	    
	    char UserAskQX;
	    cin >> UserAskQX;
	    if (UserAskQX != 'Y' && UserAskQX != 'y') {
	        printf("\n 不同意，执行退出。");
	        Sleep(500);
	        exit(0);
	    }
	    
	    printf("\n 已申请权限\n");
	    Sleep(1000);
	    bool CSHbreak = true;
	    
	    while (CSHbreak) {
	        system("cls");
	        printf("\n ===================================\n");
	        printf(" 请选择程序文件的保存位置：\n\n");
	        
	        // 显示所有可用驱动器
	        DWORD drives = GetLogicalDrives();
	        char cDriveLetter = 'A';
	        int removableCount = 0; // 计数可移动磁盘
	        std::string removableDrives; // 存储可移动磁盘信息
	        
	        while (drives) {
	            if (drives & 1) {
	                char szDriveName[4] = {cDriveLetter, ':', '\\', '\0'};
	                DWORD dwDriveType = GetDriveTypeA(szDriveName);
	                
	                if (dwDriveType == DRIVE_FIXED || dwDriveType == DRIVE_REMOVABLE) {
	                    cout << " " << szDriveName[0] << " 盘";
	                    
	                    // 检测可移动磁盘
	                    if (dwDriveType == DRIVE_REMOVABLE) {
	                        removableCount++;
	                        removableDrives += szDriveName[0]; // 添加盘符到字符串
	                        removableDrives += "盘  "; // 添加空格分隔
	                    }
	                    
	                    // 获取磁盘空间信息
	                    ULARGE_INTEGER freeBytesAvailable, totalBytes, totalFreeBytes;
	                    if (GetDiskFreeSpaceEx(szDriveName, &freeBytesAvailable, &totalBytes, &totalFreeBytes)) {
	                        double totalGB = static_cast<double>(totalBytes.QuadPart);
	                        double freeGB = static_cast<double>(totalFreeBytes.QuadPart);
	                        double usedGB = totalGB - freeGB;
	                        showProgressBar(usedGB, totalGB, 33);
	                    } else {
	                        cout << " 无法获取磁盘信息。\n";
	                    }
	                }
	            }
	            drives >>= 1;
	            cDriveLetter++;
	        }
	        
	        if (removableCount > 0) {
	            std::cout << " 检测到可移动磁盘：" << removableDrives << "\n 在可移动磁盘中进行程序数据保存可能\n 会丢失程序数据，建议保存在计算机的\n 固定磁盘中。\n";
	        }
	        
	        printf(" ===================================\n");
	        printf("\n 请输入：");
	        std::string UserCFile;
	        cin >> UserCFile;
	        
	        if (UserCFile == "0") {
	            break;
	        } else if (UserCFile.size() >= 1) {
	            char selectedDrive = toupper(UserCFile[0]);
	            if (selectedDrive >= 'A' && selectedDrive <= 'Z') {
	                std::string selectedDriveStr = std::string(1, selectedDrive) + ":";
	                DWORD dwDriveType = GetDriveTypeA(selectedDriveStr.c_str());
	                
	                if (dwDriveType == DRIVE_FIXED || dwDriveType == DRIVE_REMOVABLE) {
	                    driveLetter = selectedDriveStr;
	                    CSHbreak = false;
	                    printf(" 完成更改，地址更新为：%s 盘\n", driveLetter.c_str());
	                } else {
	                    printf("\n 输入的盘符不存在或无效！\n");
	                    Sleep(1000);
	                }
	            } else {
	                printf("\n 输入错误!请输入一个正确的盘符！");
	                Sleep(1000);
	            }
	        } else {
	            printf("\n 输入错误!请输入一个正确的盘符！");
	            Sleep(1000);
	        }
	    }
	    
	    // 创建文件夹
	    std::string folderPathMain = driveLetter + "\\Clever Eletrician";
	    std::string folderPathData = driveLetter + "\\Clever Eletrician\\ProgramData";
	    std::string folderPathPic = driveLetter + "\\Clever Eletrician\\Pic";
	    _mkdir(folderPathMain.c_str());
	    _mkdir(folderPathData.c_str());
	    _mkdir(folderPathPic.c_str());
	    
	    // 写入配置
	    UserSetFile("WRITE", "Driveletter", driveLetter);
	    Sleep(1500);
	    system("cls");
	}
	
	
	// 确保配置文件存在
	std::string userSettingPath = driveLetter + "\\Clever Eletrician\\ProgramData\\UserSetting.Set";
	FILE* settingFilePtr = fopen(userSettingPath.c_str(), "r");
	if (!settingFilePtr) {
	    settingFilePtr = fopen(userSettingPath.c_str(), "w");
	    if (settingFilePtr) {
	        printf(" 创建配置文件：%s\n", userSettingPath.c_str());
	        fclose(settingFilePtr);
	    }
	} else {
	    fclose(settingFilePtr);
	}
	
	DWORD threadId;
	stopShowWindowThread = false;
	
	DeleteMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE, MF_BYCOMMAND);
	// 删除最大化按钮
    SetWindowLong(GetConsoleWindow(), GWL_STYLE, GetWindowLong(GetConsoleWindow(), GWL_STYLE) & ~WS_MAXIMIZEBOX);
	DrawMenuBar(GetConsoleWindow());
	// 刷新窗口，使更改生效
	SetWindowPos(GetConsoleWindow(), NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
	
	CreateThread(NULL, 0, Showwindow_Thread, NULL, 0, NULL);// 创建线程
	CreateThread(NULL, 32, ProgramPicture_Thread, 0, 0, &threadId); // 创建线程 , 启动刷新显示的线程
	CreateThread(NULL, 0, ResetShottime_Thread, NULL, 0, NULL);	//创建线程
	CreateThread(NULL, 32, AutoColor_Thread, 0, 0, &threadId); // 创建线程 , 启动刷新显示的线程
	CreateThread(NULL, 0, RefreshDisplay, NULL, 0, NULL);
	
    // 替换为您程序所在的文件夹路径
    std::string folderPath = driveLetter + "\\Clever Eletrician"; // 将两个字符串连接起来
    
    // 替换为您的文件路径
    std::string Programpath = FindPath("聪明的电教员.exe");
	const char* fileToHidePath = Programpath.c_str(); // 源程序路径
	
	//创建文件
	std::string ShutdownTimeF = driveLetter + "\\Clever Eletrician\\ProgramData\\SetShutdown.time";
	FILE *ShutdownFile = fopen(ShutdownTimeF.c_str(), "a"); // 使用 c_str() 获取 C 风格字符串
	
	std::string SleepDisplayTimeF = driveLetter + "\\Clever Eletrician\\ProgramData\\SleepDisplay.time";
	FILE *SleepDisplayFile = fopen(SleepDisplayTimeF.c_str(), "a"); // 使用 c_str() 获取 C 风格字符串
	
	std::string RebootTimehourF = driveLetter + "\\Clever Eletrician\\ProgramData\\SetReboot.time";
	FILE *SetRebootFile = fopen(RebootTimehourF.c_str(), "a");
	
	// DayDiary_file 文件
	std::string DayDiaryFileF = driveLetter + "\\Clever Eletrician\\ProgramData\\DayDiary_file.Log";
	FILE *DayDiary_file = fopen(DayDiaryFileF.c_str(), "a");
	
	fseek(ShutdownFile, 0, SEEK_END); //范围从0起始位至末尾，统计关机文件大小
	fseek(SleepDisplayFile, 0, SEEK_END); //范围从0起始位至末尾，统计睡眠文件大小
	Jiance = ftell(ShutdownFile); //判断文件大小
	int SJiance = ftell(SleepDisplayFile);
	fclose(ShutdownFile); // 确保文件被关闭
	fclose(SleepDisplayFile); // 确保文件被关闭
 
	time_t now = time(NULL);
	struct tm* local_time = localtime(&now);
 
 	fopen(DayDiaryFileF.c_str(), "a");
	fprintf(DayDiary_file, "\n\n程序启动时间： %d年 %d月 %d日 %d:%02d \n",
	        local_time->tm_year + 1900,
	        local_time->tm_mon + 1,
	        local_time->tm_mday,
	        local_time->tm_hour,
	        local_time->tm_min
	);
	fprintf(DayDiary_file, "聪明的电教员 程序已启动\n");
	fprintf(DayDiary_file, "用户已进入到“主菜单”");
	
    // 设置文件的属性为隐藏
    if(UserSetFile("GET", "Filehide") == "T"){
    	SetFileAttributes(fileToHidePath, FILE_ATTRIBUTE_HIDDEN);
    	fprintf(DayDiary_file, "\n程序目前状态为：隐藏");
	}
	else{
		SetFileAttributes(fileToHidePath, FILE_ATTRIBUTE_NORMAL);
		fprintf(DayDiary_file, "\n程序目前状态为：显示");
	}
	
	if(UserSetFile("GET", "CreateLnk") == "T"){
		ComputerCrateFL("CreateProgramStartLnk");
	}		
	if (UserSetFile("GET", "FirstStartMinimized") == "T" && needInit == false) {
		ShowWindow(GetConsoleWindow(), SW_MINIMIZE); //启动时最小化窗口
		fprintf(DayDiary_file, "\n用户开启了启动时最小化窗口");
	}
	if (UserSetFile("GET", "Autolock") == "T") {
		CreateThread(NULL, 0, AutoLock_Thread, NULL, 0, NULL);	//创建线程
		fprintf(DayDiary_file, "\n用户开启了程序自锁定功能");
	}
	if (Jiance != 0) {
		hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);  // Manual reset, initially non-signaled
	}
	
	// 上面两句也可以换成
	// EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE, MF_GRAYED);
	//printf("关闭按钮按不了了\n");
	//int main(){
	// HWND hwnd = GetConsoleWindow();
	// LONG Style;    //窗口风格
	// Style = GetWindowLong(hwnd, GWL_STYLE);   // 得到窗口风格
	// Style = Style & ~WS_CAPTION;             //去掉标题栏
	// SetWindowLong(hwnd, GWL_STYLE, Style);     //为窗口设置新的风格
	// printf("关闭按钮不见了\n");
	//}
	//https://zhidao.baidu.com/question/683406533724209372.html
 
	bool ScilentShut = false;
	if (UserSetFile("GET", "SilentShutdown") == "T") {
		ScilentShut = true;
	}
	bool PowerOff = false;
	bool FirstLogin = false;
	bool Logsuccess = true;
	bool issign = true;
	
	// 界面显示
	while (true) {
		string Checklockkey = UserSetFile("GET", "LOCK");
 		string CheckShutkey = UserSetFile("GET", "SHOUTDOWN");
		string Checksleepkey = UserSetFile("GET", "SLEEP");
		string Checkrebootkey = UserSetFile("GET", "REBOOT");
		
		if (Checklockkey == "T") {
			system(" color 0F"); //可以写成 red 调出颜色组
			while (Logsuccess) {
				if(FirstLogin == true){
					break;
				}
				printf("\n 欢迎使用程序“聪明的电教员”！");
				if (CheckShutkey == "T" || Checksleepkey == "T" || Checkrebootkey == "T" || CheckShutkey == "T") {
					printf("\n ---------状态栏---------");
				}
				if (CheckShutkey == "T") {
					printf(" \n  距离下一次关机还有:\n  ");
					Computer_Power_Off("", PowerOff, ScilentShut);
					fprintf(DayDiary_file, "\n %s", "关机模块已启动");
					fclose(DayDiary_file);
					
				}
				if (Checkrebootkey == "T") {
					printf(" \n  距离下一次重启还有:\n  ");
					Computer_Power_Off("Reboot", PowerOff, ScilentShut);
					fprintf(DayDiary_file, "\n %s", "关机模块已启动");
					fclose(DayDiary_file);
					
				}
				if (Checksleepkey == "T") {
					printf(" \n  距离下一次睡眠还有:\n  ");
					Computer_Display_Sleep("");
					printf(" ------------------------");
					fprintf(DayDiary_file, "\n %s", "睡眠模块已启动");
					fclose(DayDiary_file);
				}
				if (CheckShutkey == "T" && Checksleepkey != "T") {
					printf("\n ------------------------");
				}
				fclose(DayDiary_file);
				srand(time(nullptr));
				if (!checkFileExists()) {
					cout << "\n 未找到注册用户信息，请先进行注册。" << endl;
					cout << " 需要注册吗？建议注册以保护信息。【1 取消 任意键（继续）】" << endl;
					cout << " 请输入：";
					cin >> UserInput;
					if(UserInput == 1){
						FirstLogin = true;
						break;
					}
					else{
						while (!registerUser()) {
						}
						issign = false;
					}
				}
				if (!UserSetFile("GET", "password").empty()) {
				    string encryptedDataFromFile = UserSetFile("GET", "password");
				    size_t spacePos = encryptedDataFromFile.find(',');
				    if (spacePos == std::string::npos) {
					    std::string encryptedUser = encryptedDataFromFile.substr(0, spacePos);
						cout << "\n 检测到用户信息异常，请重新注册。" << endl;
						cout << " 需要重新注册吗？建议重新注册以保护信息。【1 取消 任意键（继续）】" << endl;
						cout << " 请输入：";
						cin >> UserInput;
						if(UserInput == 1){
							FirstLogin = true;
							break;
						}
						else{
							while (!registerUser()) {
							}
							issign = false;
						}
					}
				}
				if (issign == false) {
					Sleep(500);
					Logsuccess = false;
					if (hMutex == NULL || GetLastError() == ERROR_ALREADY_EXISTS) {
				        // 释放互斥体句柄
				        if (hMutex != NULL) {
				            CloseHandle(hMutex);
				        }
				        // 关闭先前的实例
				        HWND hwnd = FindWindow(NULL, "Your Program Window Title");
				        if (hwnd != NULL) {
				            PostMessage(hwnd, WM_CLOSE, 0, 0);
				        }
				        // 启动一个新的实例
				        ShellExecute(NULL, "open", PROGRAM_FILENAME, NULL, NULL, SW_SHOWNORMAL);
				    }
				} else if (login() == false) {
					continue;
				} else {
					Logsuccess = false;
				}
			}
			FirstLogin = true;
			Sleep(250);
			system("cls");
		}
		// 时间栏与界面样式
		// 主界面样式
		HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
	    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
	    
	    if(UserSetFile("GET", "DarkColor") == "F"){
			system(" color F0"); //可以写成 red 调出颜色组
		}
		
		if (ProgramAuto == 0) { //检测启动后开机自启动函数
			ComputerCrateFL("CreateStartProgram"); //如果为0（未启用），则执行
			ProgramAuto++;
		} else {
			system("cls");//反之则清屏
		}
		
		printf("\n\n      |聪明的电教员|");
		printf("\n\n =========菜单栏=========");
		printf("\n  1.定时关闭/睡眠计算机\n");
		printf("  2.快捷功能\n");
		printf("  3.设置\n");
		printf("  用键盘输入功能所对应\n  的数字即可(0退出功能) \n");
		printf(" ========================");
		cout<<"["<<driveLetter<<"]";
		if (CheckShutkey == "T" || Checksleepkey == "T" || Checkrebootkey == "T") {
			printf("\n ---------状态栏---------");
		}
		if (CheckShutkey == "T") {
			printf(" \n  距离下一次关机还有:\n  ");
			Computer_Power_Off("", PowerOff, ScilentShut);
			fprintf(DayDiary_file, "\n %s", "关机模块已启动");
			fclose(DayDiary_file);
		}
		if (Checkrebootkey == "T") {
			printf(" \n  距离下一次重启还有:\n  ");
			Computer_Power_Off("Reboot", PowerOff, ScilentShut);
			fprintf(DayDiary_file, "\n %s", "重启模块已启动");
			fclose(DayDiary_file);
		}
		if (Checksleepkey == "T") {
			printf(" \n  距离下一次睡眠还有:\n  ");
			Computer_Display_Sleep("");
			printf(" ------------------------");
			fprintf(DayDiary_file, "\n %s", "睡眠模块已启动");
			fclose(DayDiary_file);
		}
		if (CheckShutkey == "T" && Checksleepkey != "T") {
			printf("\n ------------------------");
		}
		printf("\n 请输入：");//文字菜单栏
		string *s = new string;
		cin >> *s;
		if (s->length() > 1 || '0' > (*s)[0] || (*s)[0] > '3' ) {
			printf("\n 错误！无效的输入！");
			Sleep(500);
			system("cls");
			continue;
		}
		UserInput = (*s)[0] - '0';
		delete s;
		
		if (UserInput == 1) {
			bool CbreakSetTime = true;
			while (CbreakSetTime) {
				system("cls");
				printf("\n ===定时关闭/睡眠计算机===\n");
				printf(" 1.定时关闭计算机\n");
				printf(" 2.定时睡眠计算机\n");
				printf(" 3.定时重启计算机\n");
				printf(" ========================\n");
				printf("\n 请输入：");
 
				std::unique_ptr<std::string> s = std::make_unique<std::string>();
				std::cin >> *s;
				
				// 根据 KeyCMax 调整有效输入范围
		        if (s->length() > 1 || (*s)[0] < '0' || (*s)[0] > '3') {
		            printf("\n 错误！无效的输入！");
		            Sleep(500);
		            continue;
		        }
				
				UserInput = (*s)[0] - '0';
				if (UserInput == 0) {
					CbreakSetTime = false;
				}
				if (UserInput == 1) {
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n", "用户选择了功能“定时关闭计算机”");
					fclose(DayDiary_file);
					ComputerProgramUserInput("Shutdown"); //调用 ComputerProgramUserInput() 函数，也就是输入电脑的关机时间段
					CbreakSetTime = false;
					continue;
				}
				if (UserInput == 2) {
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n", "用户选择了功能“定时睡眠计算机”");
					fclose(DayDiary_file);
					ComputerProgramUserInput("Sleep"); //调用 ComputerProgramUserInput() 函数，也就是输入电脑的关机时间段
					CbreakSetTime = false;
					continue;
				}
				if (UserInput == 3) {
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n", "用户选择了功能“定时重启计算机”");
					fclose(DayDiary_file);
					ComputerProgramUserInput("Reboot"); //调用 ComputerProgramUserInput() 函数，也就是输入电脑的关机时间段
					CbreakSetTime = false;
					continue;
				}
			}
		} else if (UserInput == 2) {
			fopen(DayDiaryFileF.c_str(), "a");
			fprintf(DayDiary_file, "%s \n", "用户在功能“快捷功能 ”");
			bool CbreakCon = true;
			char lim = '3';
			Jiance = ftell(ShutdownFile); //判断文件大小
			while (CbreakCon) {
				system("cls");
				printf("\n =======快捷功能========\n");
				printf(" 1.立即关闭计算机\n");
				printf(" 2.取消计算机的关机任务\n");
				printf(" 3.跳过计算机的关机任务\n");
				if(Jiance > 0){
					lim = '4';
					printf(" 4.查看计算机的关机任务\n");
				}
				printf(" ========================\n");
				printf("\n 请输入：");
 
				std::unique_ptr<std::string> s = std::make_unique<std::string>(); // 创建智能指针
		        std::cin >> *s; // 输入数据到智能指针指向的 std::string
		
		        // 验证输入是否符合要求
		        if (s->length() > 1 || (*s)[0] < '0' || (*s)[0] > lim) {
		            printf("\n 错误！无效的输入！");
		            Sleep(500); // 延迟 500 毫秒
		            system("cls"); // 清屏
		            continue; // 继续循环等待正确输入
		        }
		
		        // 转换输入为整数
		        UserInput = (*s)[0] - '0';
		        
				if (UserInput == 0) {
					CbreakCon = false;
				}
				if (UserInput == 1) {
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n", "用户选择了功能“立即关闭计算机”");
					system("shutdown -a");
					system("shutdown -s -t 15");
					printf("\n 执行立即关闭计算机");
					Sleep(1000);
					ShowWindow(GetConsoleWindow(), SW_MINIMIZE);//启动时最小化窗口
					Sleep(500);
					break;
				}
				if (UserInput == 2) {
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n\n", "用户选择了功能“立即关闭计算机”");
					system("shutdown -a");
 
					printf(" ========================");
					printf("\n  用户取消关机完成");
					printf("\n ========================\n");
 
					fprintf(DayDiary_file, "%s \n", "用户正确取消关机完成");
					Sleep(1500);
					exit(0);
				}
				if (UserInput == 3) {
					PowerOff = true;
					system("shutdown -a");
					printf(" 完成\n ");
					Sleep(1500);
					continue;
									
				}
				if (UserInput == 4 and Jiance > 0) {
				    if (Jiance == 0 && SJiance == 0) {
				        printf(" 没有任务，你可以在“定时关闭/睡眠计算机”中设定任务。\n ");
				        system("pause");
				        continue;
				    }
				    if (Jiance == 0) {
				        printf(" 没有关机任务，你可以在“定时关闭/睡眠计算机”中设定关机任务。\n ");
				    }
				    if (Jiance != 0) {
				        fopen(DayDiaryFileF.c_str(), "a");
				        fprintf(DayDiary_file, "%s \n", "用户选择了功能 “查看计算机的关机任务 ”");
				
				        // 打开合并后的文件
				        std::string filePath = driveLetter + "\\Clever Eletrician\\ProgramData\\SetShutdown.time";
				        FILE *fin = fopen(filePath.c_str(), "r");
				
				        if (fin == NULL) {
				            fprintf(DayDiary_file, "%s \n", "错误：用户无法打开对应的文件，文件可能已经损坏或删除!");
				            printf(" 错误：无法打开对应的文件，文件可能已经损坏或删除!\n");
				            exit(0);
				        }
				
				        int hour, minute, weekday, line = 0;
				        std::vector<int> hours, minutes, weekdays;
				
				        // 逐行读取文件内容
				        while (fscanf(fin, "%d:%d[%d]", &hour, &minute, &weekday) == 3) {
				            hours.push_back(hour);
				            minutes.push_back(minute);
				            weekdays.push_back(weekday);
				            line++;
				        }
				        fclose(fin);
				
				        if (line == 0) {
				            printf(" 没有设定任何关机任务。\n");
				        } else {
				            printf(" 你一共设定了 %d 项关机任务。\n", line);
				            for (int i = 0; i < line; i++) {
				                printf(" 第%d项任务：", i + 1);
				                printf(" %d 时 ", hours[i]);
				                printf(" %d 分 ", minutes[i]);
				                switch (weekdays[i]) {
				                    case 0:
				                        cout << " 全周 ";
				                        break;
				                    case 1:
				                        cout << "周一 ";
				                        break;
				                    case 2:
				                        cout << "周二 ";
				                        break;
				                    case 3:
				                        cout << "周三 ";
				                        break;
				                    case 4:
				                        cout << "周四 ";
				                        break;
				                    case 5:
				                        cout << "周五 ";
				                        break;
				                    case 6:
				                        cout << "周六 ";
				                        break;
				                    case 7:
				                        cout << "周天 ";
				                        break;
				                    default:
				                        cout << "未知 ";
				                        break;
				                }
				                cout << "\n";
				            }
				        }
				    }
				
				    if (SJiance == 0) {
				        printf("\n 没有睡眠任务，你可以在“定时关闭/睡眠计算机”中设定睡眠任务。\n ");
				        system("pause");
				        continue;
				    }
				
				    // 保留睡眠任务的处理逻辑
					std::string SfilePath = driveLetter + "\\Clever Eletrician\\ProgramData\\SleepDisplay.time";
					FILE *Sfin = fopen(SfilePath.c_str(), "r");
					
					if (Sfin == NULL) {
					    fopen(DayDiaryFileF.c_str(), "a");
					    fprintf(DayDiary_file, "%s \n", "错误：用户无法打开对应的文件，文件可能已经损坏或删除!");
					    printf(" 错误：无法打开对应的文件，文件可能已经损坏或删除!\n");
					    exit(0);
					}
					
					// 统计行数
					int Sc, Slc = 0; // c为文件当前字符，lc为上一个字符，供结尾判断用。
					int Sline = 0;   // 行数统计
					while ((Sc = fgetc(Sfin)) != EOF) { // 逐个读入字符直到文件结尾
					    if (Sc == '\n')
					        Sline++; // 统计行数
					    Slc = Sc;   // 保存上一字符
					}
					if (Slc != '\n')
					    Sline++; // 处理末行
					
					rewind(Sfin); // 重置文件指针到开头
					
					// 动态分配内存
					SleepTime St;
					St.A = (int *)malloc(sizeof(int) * Sline); // 定义变量名 computer_hour
					St.A2 = (int *)malloc(sizeof(int) * Sline); // 定义变量名 computer_minute
					
					// 读入并解析数据
					printf("\n");
					int Si = 0;
					for (Si = 0; Si < Sline; Si++) {
					    int hour, minute;
					    if (fscanf(Sfin, "%d:%d", &hour, &minute) == 2) { // 按格式读取小时和分钟
					        St.A[Si] = hour;
					        St.A2[Si] = minute;
					    } else {
					        printf(" 错误：文件格式不正确，无法解析数据。\n");
					        fclose(Sfin);
					        free(St.A);
					        free(St.A2);
					    }
					}
					
					fclose(Sfin); // 关闭文件
					
					// 打印任务信息
					printf(" 你一共设定了 %d 项睡眠任务。\n", Sline);
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n", "用户已退出该功能，进入到“主菜单”");
					
					for (int list = 0; list < Sline; list++) {
					    printf(" 第%d项任务：", list + 1);
					    printf(" %d 时 ", St.A[list]);
					    printf(" %d 分 ", St.A2[list]);
					    cout << "\n";
					}
					
					printf("\n ");
					system("pause");
					system("cls");
					
					// 释放动态分配的内存
					free(St.A);
					free(St.A2);
					
				 	St.A = nullptr;
				 	St.A2 = nullptr;
					
					// 继续主程序逻辑
					continue;
				}
			}	
 
		} else if (UserInput == 3) {
			fopen(DayDiaryFileF.c_str(), "a");
			fprintf(DayDiary_file, "%s \n", "\n用户选择了功能“设置 ”");
			bool CbreakSet = true;
			while (CbreakSet) {
				HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
			    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
			    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
			    WORD defaultAttributes = consoleInfo.wAttributes;  // 获取默认的文本属性
			    
				std::string encryptedDataFromFile = "N/A";
				std::string User = "N/A";
			    size_t spacePos;
				if (!UserSetFile("GET", "password").empty()) {
				    encryptedDataFromFile = UserSetFile("GET", "password");
				    spacePos = encryptedDataFromFile.find(',');
				    if (spacePos == std::string::npos) {
				        User = "ERROR";
				    }
				    else{
						std::string encryptedUser = encryptedDataFromFile.substr(0, spacePos);
						User = decrypt(encryptedUser);
					}
				}
				
				//界面样式
				system("cls");
				printf("\n ==========设置==========\n");
				if (User == "N/A") {
					// 设置灰色文字，保留当前背景色
				    SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | (defaultAttributes & 0xF0));
					// 恢复默认颜色
					cout << " [未注册]";
					// 恢复默认颜色
					SetConsoleTextAttribute(hConsole, defaultAttributes);
					cout << "请您注册\n";
				} 
				else if(User == "ERROR"){
					// 设置红色文字，保留当前背景色
					SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
					// 恢复默认颜色
					cout << " [注册异常]";
					// 恢复默认颜色
					SetConsoleTextAttribute(hConsole, defaultAttributes);
					cout << "注册信息异常\n";
				}
				else {
					cout << " [已注册]用户：" << User << "\n";
				}
				printf(" ------------------------\n");
				printf(" 1.文件数据管理\n");
				printf(" 2.程序级设置\n");
				printf(" 3.用户个性化\n");
				printf(" 4.关于\n");
				printf(" ========================\n");
				printf("\n 请输入：");
				
				std::unique_ptr<std::string> s = std::make_unique<std::string>(); // 创建智能指针
		        std::cin >> *s; // 输入数据到智能指针指向的 std::string
		
		        // 验证输入是否符合要求
		        if (s->length() > 1 || (*s)[0] < '0' || (*s)[0] > '4') {
		            printf("\n 错误！无效的输入！");
		            Sleep(500); // 延迟 500 毫秒
		            system("cls"); // 清屏
		            continue; // 继续循环等待正确输入
		        }
 
				// 转换输入为整数
				UserInput = (*s)[0] - '0';
 
				if (UserInput == 0) {
					CbreakSet = false;
				}
				if (UserInput == 1) {
					bool CbreakFile = true;
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n", "\n用户选择了功能“文件数据管理 ”");
					while (CbreakFile) {
						system("cls");
						printf("\n ======文件数据管理======\n");
						printf(" 文件存储位置:"); // 打印字符串的第一个字符
						printf(" %c 盘" , driveLetter[0]);
						printf("\n ------------------------\n");
						printf(" 1.删除日志记录\n");
						printf(" 2.删除已保存的数据\n");
						printf(" 3.更改程序文件的存储位置\n");
						printf(" ========================\n");
						printf("\n 请输入：");
						UserInput = 0;
						
						std::unique_ptr<std::string> s = std::make_unique<std::string>(); // 创建智能指针
				        std::cin >> *s; // 输入数据到智能指针指向的 std::string
				
				        // 验证输入是否符合要求
				        if (s->length() > 1 || (*s)[0] < '0' || (*s)[0] > '4') {
				            printf("\n 错误！无效的输入！");
				            Sleep(500); // 延迟 500 毫秒
				            system("cls"); // 清屏
				            continue; // 继续循环等待正确输入
				        }
		 
						// 转换输入为整数
						UserInput = (*s)[0] - '0';
						
						if (UserInput == 0) {
							CbreakFile = false;
						}
 
						if (UserInput == 1) {
							fclose(DayDiary_file);
 
							std::string DayDiaryFilePath = driveLetter + "\\Clever Eletrician\\ProgramData\\DayDiary_file.Log";
							fopen(DayDiaryFilePath.c_str(), "w");
							
							printf("\n Done\n");
							Sleep(1000);
							continue;
						}
 
						if (UserInput == 2) {
						    // --------------------------
						    // 步骤1：扫描所有盘符的程序存储文件夹，记录有效盘符
						    // --------------------------
						    std::vector<std::string> validDrives; // 存储存在Clever Eletrician的盘符
						    printf("\n ===================================\n");
						    printf(" 正在扫描计算机中的程序存储文件夹...\n");
						    printf(" ===================================\n");
						    
						    // 遍历C-Z盘符，检查Clever Eletrician文件夹是否存在（无C++11特性，无需改）
						    for (char drive = 'C'; drive <= 'Z'; ++drive) {
						        std::string checkPath = std::string(1, drive) + ":\\Clever Eletrician";
						        if (_access(checkPath.c_str(), 0) != -1) { // 0表示检查文件/文件夹是否存在
						            validDrives.push_back(std::string(1, drive)); // 记录盘符（如"C"）
						        }
						    }
						    system("cls"); // 清屏
						
						    // 步骤2：美观列出扫描结果（无C++11特性，无需改）
						    if (validDrives.empty()) {
						        printf(" 未在任何盘符找到\"Clever Eletrician\"文件夹，无需删除\n");
						        Sleep(1000);
						        continue; // 无存储文件夹，返回主菜单
						    } else {
						    	system("cls");
								std::string UserCFile = "";
								printf("\n ===================================\n");
								printf(" 程序文件的保存位置：\n");
								
								// 存储有效盘符（存在程序存储文件夹）的可移动磁盘信息
								int removableCount = 0;
								std::string removableDrives;
								
								cout << "\n";
								// 只遍历存在程序存储文件夹的盘符（validDrives）
								for (size_t i = 0; i < validDrives.size(); ++i) {
								    // 构建盘符路径（如"C:\"）
								    char szDriveName[4] = {validDrives[i][0], ':', '\\', '\0'};
								    DWORD dwDriveType = GetDriveTypeA(szDriveName);
								
								    // 只处理固定磁盘和可移动磁盘（与原有逻辑一致）
								    if (dwDriveType == DRIVE_FIXED || dwDriveType == DRIVE_REMOVABLE) {
								        cout << " " << szDriveName[0] << " 盘";
								        
								        // 检测可移动磁盘并记录
								        if (dwDriveType == DRIVE_REMOVABLE) {
								            removableCount++;
								            removableDrives += szDriveName[0];
								            removableDrives += "盘  ";
								        }
								
								        // 获取磁盘空间信息并调用内置进度条函数
								        ULARGE_INTEGER freeBytesAvailable, totalBytes, totalFreeBytes;
								        if (GetDiskFreeSpaceEx(szDriveName, &freeBytesAvailable, &totalBytes, &totalFreeBytes)) {
								            // 转换为GB单位（适配进度条函数的数值范围）
								            double totalGB = static_cast<double>(totalBytes.QuadPart);
								            double freeGB = static_cast<double>(totalFreeBytes.QuadPart);
								            double usedGB = totalGB - freeGB;
								
								            // 调用内置的进度条显示函数（保持原有参数格式）
								            showProgressBar(usedGB, totalGB, 33);
								        } else {
								            cout << " 无法获取磁盘信息。\n";
								        }
								    }
								}
								
								// 输出可移动磁盘警告信息（仅针对有效盘符中的可移动磁盘）
								if (removableCount > 0) {
								    std::cout << " 检测到可移动磁盘：" << removableDrives << "\n 在可移动磁盘中进行程序数据保存可能\n 会丢失程序数据，建议保存在计算机的\n 固定磁盘中。\n";
								}
								printf(" -----------------------------------\n");
						    }
						
						    // --------------------------
						    // 步骤3：用户选择性输入要删除的盘符（核心修改：替换C++11特性）
						    // --------------------------
						    std::vector<std::string> selectedDrives; // 存储用户选择的删除盘符
						    char inputBuf[128] = {0};
						    printf(" 请输入要删除数据的盘符（格式说明）：\n");
						    printf(" - 单个盘符：直接输入，如「c」\n");
						    printf(" - 多个盘符：用空格分隔，如「c d e」\n");
						    printf(" ===================================\n");
						    printf(" 请输入：");
						    // 先清理cin缓冲区（原逻辑位置调整：确保读取输入前无残留换行）
						    if (cin.peek() == '\n') cin.ignore();
						    cin.getline(inputBuf, sizeof(inputBuf)); // 处理带空格的输入
						
						    // 分割输入字符串，提取盘符（忽略大小写）
						    std::string inputStr = inputBuf;
						    std::string temp;
						    // 【修改1：替换C++11范围for为传统索引循环】
						    for (size_t i = 0; i < inputStr.size(); ++i) {
						        char c = inputStr[i]; // 按索引取字符
						        if (c == ' ' || c == '\t') { // 空格/制表符分隔
						            if (!temp.empty()) {
						                // 转大写：用toupper（兼容旧编译器，避免_toupper的兼容性问题）
						                char upperFirst = toupper(static_cast<unsigned char>(temp[0]));
						                selectedDrives.push_back(std::string(1, upperFirst) + temp.substr(1));
						                temp.clear();
						            }
						        } else if (isalpha(static_cast<unsigned char>(c))) { // 只保留字母字符（防负数ASCII）
						            temp += toupper(static_cast<unsigned char>(c)); // 转大写后存入临时变量
						        }
						    }
						    // 处理最后一个盘符
						    if (!temp.empty()) {
						        char upperFirst = toupper(static_cast<unsigned char>(temp[0]));
						        selectedDrives.push_back(std::string(1, upperFirst) + temp.substr(1));
						    }
						
						    // 验证选择的盘符是否在有效列表中，过滤无效值
						    std::vector<std::string> filteredDrives;
						    // 【修改2：替换C++11 auto为显式迭代器类型】
						    std::vector<std::string>::const_iterator driveIt; // 显式声明const迭代器
						    for (driveIt = selectedDrives.begin(); driveIt != selectedDrives.end(); ++driveIt) {
						        const std::string& drive = *driveIt; // 解引用迭代器获取当前盘符
						        // 检查是否为单个字母（如"C"，排除"C:"等无效格式）
						        if (drive.size() == 1 && isalpha(static_cast<unsigned char>(drive[0]))) {
						            // 【修改3：替换auto为显式迭代器类型】
						            std::vector<std::string>::iterator findIt; // 显式声明迭代器
						            findIt = std::find(validDrives.begin(), validDrives.end(), drive);
						            if (findIt != validDrives.end()) {
						                filteredDrives.push_back(drive);
						            } else {
						                printf(" \n 警告：%s盘未找到程序存储文件夹，已跳过\n", drive.c_str());
						            }
						        } else {
						            printf(" \n 警告：「%s」不是有效盘符格式，已跳过\n", drive.c_str());
						        }
						    }
						
						    // 无有效选择时返回主菜单（无C++11特性，无需改）
						    if (filteredDrives.empty()) {
						        printf(" \n 未选择任何有效盘符，终止删除操作\n");
						        Sleep(1000);
						        continue;
						    }
						
						    // 确认用户选择的盘符（无C++11特性，无需改）
						    printf("\n ===================================\n");
						    printf(" 你选择删除以下盘符的程序数据：\n");
						    for (size_t i = 0; i < filteredDrives.size(); ++i) {
						        printf(" %d. %s盘\n",
						               i + 1,
						               filteredDrives[i].c_str(),
						               filteredDrives[i].c_str());
						    }
						    printf(" ===================================\n");
						
						    // --------------------------
						    // 步骤4：保留原有多轮确认逻辑（防止误操作）
						    // --------------------------
						    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
						    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
						    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
						    WORD defaultAttributes = consoleInfo.wAttributes;
						
						    // 首次确认：是否删除选中盘符数据（无C++11特性，无需改）
						    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
						    printf("\n 【第一次确认】\n");
						    printf(" 删除将清空选中盘符的所有程序文件，确定继续吗？【1-确定 2-取消】\n");
						    SetConsoleTextAttribute(hConsole, defaultAttributes);
						    printf(" 请输入：");
						    UserInput = 0;
						    cin >> UserInput;
						    if (UserInput != 1) {
						        // 日志记录：用户取消首次确认
						        FILE* dayLog = fopen(DayDiaryFileF.c_str(), "a");
						        if (dayLog) {
						            fprintf(dayLog, "%s \n", "用户在删除功能中，取消第一次确认，终止操作");
						            fclose(dayLog);
						        }
						        printf("\n 已取消删除，返回主菜单\n");
						        Sleep(500);
						        continue;
						    }
						
						    // 二次确认：程序重置提醒（无C++11特性，无需改）
						    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
						    printf("\n 【第二次确认】\n");
						    printf(" 删除后程序数据将重置，再次启动会进入初始化界面，确定继续吗？【1-确定 2-取消】\n");
						    SetConsoleTextAttribute(hConsole, defaultAttributes);
						    printf(" 请输入：");
						    UserInput = 0;
						    cin >> UserInput;
						    if (UserInput != 1) {
						        FILE* dayLog = fopen(DayDiaryFileF.c_str(), "a");
						        if (dayLog) {
						            fprintf(dayLog, "%s \n", "用户在删除功能中，取消第二次确认，终止操作");
						            fclose(dayLog);
						        }
						        printf("\n 已取消删除，返回主菜单\n");
						        Sleep(500);
						        continue;
						    }
						
						    // 三次确认：重启程序提醒（无C++11特性，无需改）
						    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
						    printf("\n 【第三次确认】\n");
						    printf(" 删除需要重启程序以生效，确定继续吗？【1-确定 2-取消】\n");
						    SetConsoleTextAttribute(hConsole, defaultAttributes);
						    printf(" 请输入：");
						    UserInput2 = 0;
						    cin >> UserInput2;
						    if (UserInput2 != 1) {
						        FILE* dayLog = fopen(DayDiaryFileF.c_str(), "a");
						        if (dayLog) {
						            fprintf(dayLog, "%s \n", "用户在删除功能中，取消重启确认，终止操作");
						            fclose(dayLog);
						        }
						        printf("\n 已取消删除，返回主菜单\n");
						        Sleep(500);
						        continue;
						    }
						
						    // --------------------------
						    // 步骤5：执行选择性删除（创建删除标记文件）
						    // --------------------------
						    FILE* dayLog = fopen(DayDiaryFileF.c_str(), "a");
						    if (dayLog) {
						        fprintf(dayLog, "%s \n", "用户确认删除程序数据，开始创建删除标记文件");
						        fclose(dayLog);
						    }
						
						    SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
						    printf("\n 正在为选中盘符创建删除标记...\n");
						    // 【修改4：替换C++11 auto为显式迭代器类型】
						    std::vector<std::string>::const_iterator filterIt;
						    for (filterIt = filteredDrives.begin(); filterIt != filteredDrives.end(); ++filterIt) {
						        const std::string& drive = *filterIt; // 解引用迭代器获取当前盘符
						        std::string deleteMarkPath = drive + ":\\Clever Eletrician\\ProgramData\\DeleteProgramFile.sh";
						        FILE* markFile = fopen(deleteMarkPath.c_str(), "a"); // 创建删除标记文件
						        if (markFile) {
						            fprintf(markFile, "Delete program data on %s drive\n", drive.c_str()); // 写入标记内容
						            fclose(markFile);
						            printf(" ? %s盘：删除标记创建成功（%s）\n", drive.c_str(), deleteMarkPath.c_str());
						            
						            // 日志记录单个盘符处理结果
						            FILE* logSingle = fopen(DayDiaryFileF.c_str(), "a");
						            if (logSingle) {
						                fprintf(logSingle, "已在%s盘创建删除标记文件：%s \n", drive.c_str(), deleteMarkPath.c_str());
						                fclose(logSingle);
						            }
						        } else {
						            printf(" ? %s盘：删除标记创建失败（权限不足或路径不存在）\n", drive.c_str());
						            
						            FILE* logSingle = fopen(DayDiaryFileF.c_str(), "a");
						            if (logSingle) {
						                fprintf(logSingle, "在%s盘创建删除标记文件失败 \n", drive.c_str());
						                fclose(logSingle);
						            }
						        }
						    }
						    SetConsoleTextAttribute(hConsole, defaultAttributes);
						
						    // --------------------------
						    // 步骤6：重启程序（保留原有逻辑）
						    // --------------------------
						    printf("\n ===================================\n");
						    printf(" 删除标记已创建，即将重启程序...\n");
						    printf(" ===================================\n");
						    Sleep(500);
						
						    // 释放互斥体（原有逻辑，无C++11特性）
						    if (hMutex != NULL) {
						        CloseHandle(hMutex);
						        hMutex = NULL;
						    }
						
						    // 关闭当前实例（需替换为实际窗口标题）
						    HWND hwnd = FindWindow(NULL, PROGRAM_FILENAME); // 窗口标题与实际程序一致
						    if (hwnd != NULL) {
						        PostMessage(hwnd, WM_CLOSE, 0, 0);
						        printf(" 已关闭当前程序实例\n");
						    }
						
						    // 启动新实例（路径确保正确）
						    printf("\n 已启动新程序实例\n");
						    ShellExecute(NULL, "open", PROGRAM_FILENAME, NULL, NULL, SW_SHOWNORMAL);
						    return 0;
						}
						if(UserInput == 3){
							bool CSHbreak = true;
						    olddriveletter = driveLetter;
						
						    while (CSHbreak) {
						        system("cls");
						        string UserCFile = "";
						        printf("\n ===================================");
							    printf("\n 请选择程序文件的保存位置：\n");
							
							    // 获取当前系统的所有驱动器
							    DWORD drives = GetLogicalDrives();
							    char cDriveLetter = 'A';
							    int removableCount = 0; // 计数可移动磁盘
							    std::string removableDrives; // 存储可移动磁盘信息
							
							    cout << "\n";
							    while (drives) {
							        if (drives & 1) {
							            char szDriveName[4] = {cDriveLetter, ':', '\\', '\0'};
							            DWORD dwDriveType = GetDriveTypeA(szDriveName);
							
							            if (dwDriveType == DRIVE_FIXED || dwDriveType == DRIVE_REMOVABLE) {
							                cout << " " << szDriveName[0] << " 盘";
							                
							                // 检测可移动磁盘
							                if (dwDriveType == DRIVE_REMOVABLE) {
							                    removableCount++;
							                    removableDrives += szDriveName[0]; // 添加盘符到字符串
							                    removableDrives += "盘  "; // 添加空格分隔
							                }
							
							                // 获取磁盘空间信息
							                ULARGE_INTEGER freeBytesAvailable, totalBytes, totalFreeBytes;
							                if (GetDiskFreeSpaceEx(szDriveName, &freeBytesAvailable, &totalBytes, &totalFreeBytes)) {
							                    double totalGB = static_cast<double>(totalBytes.QuadPart);
							                    double freeGB = static_cast<double>(totalFreeBytes.QuadPart);
							                    double usedGB = totalGB - freeGB;
							
							                    // 使用 showProgressBar 函数来显示进度条
							                    showProgressBar(usedGB, totalGB, 33);  // 这里的33是进度条宽度，可以根据需要调整
							                } else {
							                    cout << " 无法获取磁盘信息。\n";
							                }
							            }
							        }
							        drives >>= 1;
							        cDriveLetter++;
							    }
							
							    // 输出可移动磁盘的信息
							    if (removableCount > 0) {
							        std::cout << " 检测到可移动磁盘：" << removableDrives << "\n 在可移动磁盘中进行程序数据保存可能\n 会丢失程序数据，建议保存在计算机的\n 固定磁盘中。\n";
							    }
						
						        printf(" ===================================\n");
						        printf("\n 请输入：");
						        cin >> UserCFile;
						
						        // 处理用户输入的盘符
								char selectedDrive = toupper(UserCFile[0]);
								if (selectedDrive >= 'A' && selectedDrive <= 'Z') {
								    string selectedDriveStr = string(1, selectedDrive) + ":"; // 将字符转换为字符串形式
								
								    // 检查盘符是否存在
								    DWORD dwDriveType = GetDriveTypeA(selectedDriveStr.c_str());
								    if (dwDriveType == DRIVE_FIXED || dwDriveType == DRIVE_REMOVABLE) {
								        if (selectedDriveStr != driveLetter) {
								            driveLetter = selectedDriveStr; // 更新盘符
								            CSHbreak = false; // 退出循环
								        } else {
								            printf("\n 输入错误!请输入一个不同的盘符！");
								            Sleep(1000);
								            continue; // 继续循环
								        }
								    } else {
								        printf("\n 输入的盘符不存在或无效！\n");
								        Sleep(1000);
								        continue; // 继续循环
								    }
								} else if (UserCFile == "0") {
								    break; // 退出循环
								} else {
								    printf("\n 输入错误!请输入一个正确的盘符！");
								    Sleep(1000);
								    continue; // 继续循环
								}
						        printf(" 完成更改，地址更新为：%s 盘", driveLetter.c_str());
						    }
						    // 创建指定文件夹
						    std::string folderPathMain = driveLetter + "\\Clever Eletrician";
						    std::string folderPathData = driveLetter + "\\Clever Eletrician\\ProgramData";
						    std::string folderPathPic = driveLetter + "\\Clever Eletrician\\Pic";
						    _mkdir(folderPathMain.c_str());
						    _mkdir(folderPathData.c_str());
						    _mkdir(folderPathPic.c_str());
						    
						    UserSetFile("WRITE","Driveletter",driveLetter);
						    
						    printf("\n 更改程序存储位置需要重启程序，确定继续吗？【1 确定 2 取消（退出）】");
							UserInput2 = 0;
							printf("\n 请输入：");
							cin >> UserInput2;
							if (UserInput2 == 1) {
						        // 释放互斥体句柄
						        if (hMutex != NULL) {
						            CloseHandle(hMutex);
						        }
						        // 关闭先前的实例
						        HWND hwnd = FindWindow(NULL, PROGRAM_FILENAME);
						        if (hwnd != NULL) {
						            PostMessage(hwnd, WM_CLOSE, 0, 0);
						        }
						        // 启动一个新的实例
						        ShellExecute(NULL, "open", PROGRAM_FILENAME, NULL, NULL, SW_SHOWNORMAL);
						        exit(0);
							}
							else{
								printf("\n 取消重启");
								Sleep(500);
								continue;
							}
						    
						}
					}
				}
				
				if (UserInput == 2) {
				    bool PGbreak = true;
				    while (PGbreak) {
				        system("cls");
				        fprintf(DayDiary_file, "%s \n", "用户选择了功能“关于”");
				        
						printf("\n =======程序级设置=======\n");
						// 配置键名映射表
						const std::vector<std::string> configKeys = {
						    "ProgramAutoStart",    // 1.程序自启动
						    "CreateLnk",           // 2.创建快捷方式
						    "Filehide",            // 3.隐藏程序
						    "DarkColor",           // 4.深色模式
						    "AutoColor"            // 5.自动调整颜色模式
						};
						
						vector<string*> settingsDesc = {
						    new string("程序自启动"),
						    new string("创建快捷方式"), 
						    new string("隐藏程序"),
						    new string("深色模式"),
						};
						
						// 自动调整颜色模式条件判断
						if (UserSetFile("GET", "DarkColor") == "T") { // 改为使用AutoColor键
							settingsDesc.push_back(new string("调整颜色模式")); 
							if(UserSetFile("GET", "AutoColor") == "T"){
								settingsDesc.push_back(new string("调整设定时间")); 
							}
						}
						
						for (size_t i = 0; i < settingsDesc.size(); ++i) {
						    cout << setw(21) << left << (" " + to_string(i + 1) + "." + *settingsDesc[i]);
						    size_t foundSetMode = settingsDesc[i]->find("调整颜色模式");
						    // 处理前四个标准配置项
						    if (i < 4) {
						        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
						        CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
						        GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
						        WORD defaultAttributes = consoleInfo.wAttributes;
						
						        // 直接使用配置键名获取状态
						        std::string status = UserSetFile("GET", configKeys[i]);
						        
						        if (!status.empty()) {
						            SetConsoleTextAttribute(hConsole, 
						                (status == "T" ? FOREGROUND_GREEN : FOREGROUND_RED) | 
						                (defaultAttributes & 0xF0));
						            cout << (status == "T" ? "开启" : "关闭");
						        } else {
						            SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
						            cout << "错误";
						        }
						        SetConsoleTextAttribute(hConsole, defaultAttributes);
						    } 
						    // 处理自动颜色模式
						    else if (UserSetFile("GET", "DarkColor") == "T" && foundSetMode != string::npos) {
						        cout << "\n 设定为：" << (UserSetFile("GET", "AutoColor") == "T" ? "自动（" + UserSetFile("GET","ColorChangeTime") + "）": "手动");
						    }
						    cout << "\n";
						}
						
						// 内存释放保持不变
						for (auto ptr : settingsDesc) delete ptr;
				        
				        printf(" ========================\n");
						printf("\n\n 请输入：");
						UserInput = 0;
						string userInputStr;
						cin >> userInputStr;
						
						// 动态获取 maxX 的值，假设 x 是一个整数变量
						int maxX = settingsDesc.size(); // 设置为 '0' 到 '5' 之间的数字范围
						// TODO: 在这里设置 maxX 的实际值，可以从配置文件、用户输入等地方获取
						
						try {
						    int userInput = std::stoi(userInputStr);
						    if (userInput >= 0 && userInput <= maxX) {
						        UserInput = userInput;
						    } else {		
						        printf("\n 错误！无效的输入！");
						        Sleep(500);
						        continue;
						    }
						} catch (const std::invalid_argument& e) {
						    printf("\n 错误！无效的输入！");
						    Sleep(500);
						    continue;
						}
						
						// 通用设置切换函数
						auto ToggleSetting = [&](const std::string& key) {
						    std::string current = UserSetFile("GET", key);
						    UserSetFile("WRITE", key, (current == "T") ? "F" : "T");
						    return (current == "T") ? 0 : 1;  // 返回新状态
						};
						
						switch(UserInput) {
						    case 1: // 程序自启动和深色模式
						        ToggleSetting(configKeys[UserInput-1]);
						        Sleep(1000);
						        break;
						    
						    case 2: {  // 快捷方式管理
						        bool newState = ToggleSetting(configKeys[1]);
						        if(newState == 0) {
						            ComputerCrateFL("DeleteProgramStartLnk");
						        } else {
						            ComputerCrateFL("CreateProgramStartLnk");
						        }
						        break;
						    }
						    
						    case 3: {  // 文件隐藏
						        bool newState = ToggleSetting(configKeys[2]);
						        DWORD attrib = (newState == 0) ? FILE_ATTRIBUTE_HIDDEN : FILE_ATTRIBUTE_NORMAL;
						        SetFileAttributes(fileToHidePath, attrib);
						        Sleep(1000);
						        break;
						    }
						    
						    case 4: 
								ToggleSetting(configKeys[UserInput-1]);
								if(UserSetFile("GET", "DarkColor") == "T"){
									system(" color 0F");
								}
								else{
									system(" color F0");
								}
								break;
						    
						    case 5:  // 自动颜色模式（需要额外检查）
						        if(UserSetFile("GET", "DarkColor") == "T") {
						            ToggleSetting(configKeys[4]);
						            Sleep(1500);
						        }
						        break;
						        
						    case 6: {  // 添加块作用域
						    	cout << " 输入模式均为浅色模式生效时间，请注意。 ";
						        cout << "\n 请输入浅色模式开始小时数： ";
						        bool validInput = false;
						        int TimeData[2] = {0, 0};
						        
						        while (!validInput) {
						            // 清除输入缓冲区
						            cin.clear();
						            cin.ignore(numeric_limits<streamsize>::max(), '\n');
						            
						            if (cin >> TimeData[0]) {  // 验证输入是否为有效整数
						                if (TimeData[0] > 0 && TimeData[0] < 24) {
						                    cout << " 请输入浅色模式结束小时数： ";
						                    
						                    // 再次清除缓冲区并读取结束时间
						                    cin.clear();
						                    cin.ignore(numeric_limits<streamsize>::max(), '\n');
						                    
						                    if (cin >> TimeData[1]) {
						                        if (TimeData[1] > 0 && TimeData[1] < 24 && TimeData[1] > TimeData[0]) {
						                            validInput = true;
						                        } else {
						                            cout << " 结束时间必须大于开始时间且在1-23之间。请重新输入：" << endl;
						                            cout << " 请输入浅色模式开始小时数： ";
						                        }
						                    } else {
						                        cout << " 输入无效。请输入1-23之间的数字：" << endl;
						                        cout << " 请输入浅色模式开始小时数： ";
						                    }
						                } else {
						                    cout << " 小时数必须在1-23之间。请重新输入：" << endl;
						                    cout << " 请输入浅色模式开始小时数： ";
						                }
						            } else {
						                cout << " 输入无效，请输入数字：" << endl;
						                cout << " 请输入浅色模式开始小时数： ";
						                cin.clear();
						                cin.ignore(numeric_limits<streamsize>::max(), '\n');
						            }
						        }
						        
						        // 使用正确的字符串转换和拼接
						        string TimeResult = to_string(TimeData[0]) + "-" + to_string(TimeData[1]);
						        UserSetFile("WRITE", "ColorChangeTime", TimeResult);
						        cout << " 时间设置成功：" << TimeResult << endl;
						        Sleep(1000);
						        break;
						    }
						    
						    case 0:  // 退出
						        PGbreak = false;
						        break;
						    
						    default:
						        cout << " 无效选择，请重新输入。" << endl;
						        break;
						}
				    }
				}
				
				if (UserInput == 4) {
					fprintf(DayDiary_file, "%s \n", "用户选择了功能“关于”");
					std::string Programpath = FindPath(PROGRAM_FILENAME); // 指定程序的路径
					std::uintmax_t fileSize = get_file_size(Programpath);
					if (fileSize > 0) {
						system("cls");
						printf("\n\n 聪  明  的  电  教  员 FULL %s, Model Beta\n 程序介绍：你 厌 倦 了 每 天 都 要 关 电 脑 了 吗？或 许 这 一 款 电 教 员 程 序 可 以 帮  助 你。 它 可 以 帮 你 定 时 关 机 。\n 程序内核： C + + （ DEV  C++  6.7.5 ）\n 程序大小 ：", ProgramVersion.c_str());
						cout << format_size(fileSize);
						printf("\n 制 作 者： 2 1 0 6  班 罗 米 奇 & 2 1 1 0 班 祁 文 清 （ 2 2 1 3 李 知 博 ） ， 一 些 版  权 所 有 ， 仿 冒 必 究  ！（ 感 谢 网 上 开 源 大 佬 的 鼎 力 相 助！）\n\n                        All Rights Reserved Mialogofiend.Inc. \n");
					}
					fopen(DayDiaryFileF.c_str(), "a");
					fprintf(DayDiary_file, "%s \n", "用户已退出该功能，进入到“主菜单”");
					printf("\n ");
					system("pause");
					continue;
				}
 
				if (UserInput == 3) {
					bool Cbreak = true;
 
					while (Cbreak) {
						if(UserSetFile("GET","LOCK") == "F"){ // 检查用户是不是把进行用户登入给关闭了
							UserSetFile("WRITE","Autolock","F");  // 将程序自锁定项切换为“关闭”
						}
						
						system("cls");
						printf("\n =======用户个性化=======\n");
						vector<string*> settingsDesc = {
							new string("进行用户登入"),
							new string("进行关机计划"),
							new string("进行睡眠计划"),
							new string("进行重启计划"),
							new string("刷新关机任务(Beta)"),
							new string("静默关机时间"),
							new string("窗口自动最小化"),
							new string("窗口启动最小化"),
							new string("程序自动化锁定")
						};
						// 配置键名映射表（索引从1开始）
						const std::vector<std::string> configKeys = {
						    "LOCK",               // 1.进行用户登入
						    "SHOUTDOWN",          // 2.进行关机计划
						    "SLEEP",              // 3.进行睡眠计划
						    "REBOOT",             // 4.进行睡眠计划
						    "SilentShutdown",     // 5.刷新关机任务(Beta)
						    "SlientRun",          // 6.静默关机时间
						    "Showwindow_Thread",  // 7.窗口自动最小化
						    "FirstStartMinimized",// 8.窗口启动最小化
						    "Autolock"            // 9.程序自动化锁定
						};
						int refreshSettingIndex = settingsDesc.size() + 1; // 初始值为下一个位置
						int minimizeSettingIndex = settingsDesc.size() + 1; // 初始值为下一个位置
						int silentShutdownSettingIndex = settingsDesc.size() + 1; // 初始值为下一个位置
						int lockTimeSettingIndex = settingsDesc.size() + 1; // 初始值为下一个位置
 
						// 新增字符串及相关时间变量
						string* newSetting1 = new string("更改刷新任务时间");
						if (UserSetFile("GET", "ShutDown_Thread") == "T") { // 保存刷新任务时间的变量
							settingsDesc.push_back(newSetting1);
							refreshSettingIndex = settingsDesc.size();
						} else {
							refreshSettingIndex = -1;
						}
						string* newSetting2 = new string("更改静默关机时间");
						if (UserSetFile("GET", "SilentShutdown") == "T") { // 保存静默关机时间的变量
							settingsDesc.push_back(newSetting2);
							silentShutdownSettingIndex = settingsDesc.size();
						} else {
							silentShutdownSettingIndex = -1;
						}
						string* newSetting3 = new string("更改窗口最小化时间");
						if (UserSetFile("GET", "Showwindow_Thread") == "T") { // 保存窗口最小化时间的变量
							settingsDesc.push_back(newSetting3);
							minimizeSettingIndex = settingsDesc.size();
						} else {
							minimizeSettingIndex = -1;
						}
						
 						string* newSetting4 = new string("更改程序自锁定时间");
 						if (UserSetFile("GET", "Autolock") == "T") { // 保存程序自锁定时间的变量
 							settingsDesc.push_back(newSetting4);
 							lockTimeSettingIndex = settingsDesc.size();
 						} else {
 							lockTimeSettingIndex = -1;
 						}
 
						string* newSetting5 = new string("用户密码选项");
						// 打印设置
						for (size_t i = 0; i < settingsDesc.size(); ++i) {
							cout << setw(21) << left << (" " + to_string(i + 1) + "." + *settingsDesc[i]);
 
							// 检查是否是新增的选项
							if (i < 8) {
								// 正常显示状态信息
								HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
								CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
								GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
								
								// 修改后的代码段
								if (i < configKeys.size()) {
								    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
								    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
								    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
								    WORD defaultAttributes = consoleInfo.wAttributes;
								
								    // 获取配置状态
								    std::string status = UserSetFile("GET", configKeys[i]);
								    bool isValid = !status.empty();
								
								    if (isValid) {
								        // 设置颜色（开启：绿色，关闭：红色）
								        SetConsoleTextAttribute(hConsole, 
								            (status == "T" ? FOREGROUND_GREEN : FOREGROUND_RED) | 
								            (defaultAttributes & 0xF0));
								        
								        // 显示状态文本
								        cout << (status == "T" ? "开启" : "关闭");
								    } else {
								        // 错误状态显示
								        SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (defaultAttributes & 0xF0));
								        cout << "错误";
								    }
								
								    // 恢复默认颜色
								    SetConsoleTextAttribute(hConsole, defaultAttributes);
								}
								
								
							} else {
								// 检查是否包含关键词
								size_t foundSilentShutdown = settingsDesc[i]->find("静默关机");
								size_t foundMinimize = settingsDesc[i]->find("窗口最小化");
								size_t foundRefresh = settingsDesc[i]->find("刷新任务");
								size_t foundlocktime = settingsDesc[i]->find("锁定时间");
								if (foundRefresh != string::npos) {
									// 输出设定为刷新任务时间（以分钟为单位）
									cout << "\n 设定为：" << (std::stoi(UserSetFile("GET", "ResetShotTime")) < 0 ? "错误 " : UserSetFile("GET", "ResetShotTime")) << "秒";
								}
								// 直接输出文字而不显示状态信息
								else if (foundSilentShutdown != string::npos) {
									// 输出设定为静默关机时间（以分钟为单位）
									cout << "\n 设定为：" << (std::stoi(UserSetFile("GET", "SlientRunTime")) < 0 ? "错误 " : UserSetFile("GET", "SlientRunTime")) << "分钟";
								} 
								else if (foundMinimize != string::npos) {
									// 输出设定为窗口最小化时间（以秒为单位）
									cout << "\n 设定为：" << (std::stoi(UserSetFile("GET", "ShowwindowTime")) < 0 ? "错误 " : UserSetFile("GET", "ShowwindowTime")) << "秒";
								}
								else if (foundlocktime != string::npos) {
									// 输出设定为窗口最小化时间（以秒为单位）
									cout << "\n 设定为：" << (std::stoi(UserSetFile("GET", "Autolocktime")) < 0 ? "错误 " : UserSetFile("GET", "Autolocktime")) << "分钟";
								}
 
							}
 
							cout << "\n";
						}
 
						cout << " " << settingsDesc.size() + 1 << "." << *newSetting5 << "\n";
						
						// 释放动态分配的内存
						for (size_t i = 0; i < settingsDesc.size(); ++i) {
							delete settingsDesc[i];
						}
						delete newSetting1;
						delete newSetting2;
						delete newSetting3;
						delete newSetting4;
						delete newSetting5;
				
						cout << " silentShutdownSettingIndexNum: " << silentShutdownSettingIndex << endl;
						cout << " refreshSettingIndexNum: " << refreshSettingIndex << endl;
						cout << " minimizeSettingIndexNum: " << minimizeSettingIndex << endl;
						cout << " lockTimeSettingIndexNum: " << lockTimeSettingIndex << endl;
						printf(" ========================\n");
 						//cout<<"---"<<std::stoi(UserSetFile("GET", "ResetShotTime"))<<"---";
 
						printf("\n\n 请输入：");
						cout<<settingsDesc.size() + 1;
						UserInput = 0;
						string userInputStr;
						cin >> userInputStr;
						
						// 动态获取 maxX 的值，假设 x 是一个整数变量
						int maxX = settingsDesc.size() + 1; // 设置为 '0' 到 '11' 之间的数字范围
						// TODO: 在这里设置 maxX 的实际值，可以从配置文件、用户输入等地方获取
						
						try {
						    int userInput = std::stoi(userInputStr);
						    if (userInput >= 0 && userInput <= maxX) {
						        UserInput = userInput;
						    } else {		
						        printf("\n 错误！无效的输入！");
						        Sleep(500);
						        continue;
						    }
						} catch (const std::invalid_argument& e) {
						    printf("\n 错误！无效的输入！");
						    Sleep(500);
						    continue;
						}
						
						
						string currentSetting;
						if(UserInput > 0 && UserInput < 9){
							currentSetting = configKeys[UserInput-1];
							cout<<currentSetting<<"    ";
						}
						if ((UserInput >= 1 && UserInput <= 3) || (UserInput >= 7 && UserInput <= 8)) {
							if (UserSetFile("GET",currentSetting) == "T") {  // 如果当前设置为“开启”
								UserSetFile("WRITE", currentSetting ,"F"); // 切换为“关闭”
							} else {  // 如果当前设置为“关闭”
								UserSetFile("WRITE", currentSetting ,"T");   // 切换为“开启”
								
								if(UserInput == 8 && UserSetFile("GET","LOCK") == "F"){ // 如果用户选择了程序自锁定选择项
									printf("\n 开启此功能需要启用用户登入功能，确定继续吗？【1 确定 2 取消（退出）】");
									UserInput2 = 0;
									printf("\n 请输入：");
									cin >> UserInput2;
									if (UserInput2 == 1) {
										//ChoseKey(1, 0, UserInput2, 0,"");  // 切换为“开启”
										CreateThread(NULL, 0, AutoLock_Thread, NULL, 0, NULL);	// 创建程序自锁定线程
										continue;
									}
									else{
										printf("\n 取消开启");
										Sleep(500);
										continue;
									}
								}
							}
							Sleep(500);
							continue;
						}
 
						if (UserInput == 4) {
							if (UserSetFile("GET",currentSetting) == "T") {  // 如果当前设置为“开启”
								UserSetFile("WRITE", currentSetting ,"F"); // 切换为“关闭”
								hEvent = false;
							} else {  // 如果当前设置为“关闭”
								UserSetFile("WRITE", currentSetting ,"T");   // 切换为“开启”
								hEvent = true;
							};
							CreateThread(NULL, 0, ResetShottime_Thread, NULL, 0, NULL);	//重新创建线程
							Sleep(500);
							continue;
						}
 
						if(UserInput == 5){
							if (UserSetFile("GET",currentSetting) == "T") {  // 如果当前设置为“开启”
								UserSetFile("WRITE", currentSetting ,"F"); // 切换为“关闭”
								ScilentShut = false;
								ShutDown_ThreadMode = false;
								Sleep(1500);
							} else {  // 如果当前设置为“关闭”
								printf("\n 开启此功能需要重启程序，确定继续吗？【1 确定 2 取消（退出）】");
								UserInput2 = 0;
								printf("\n 请输入：");
								cin >> UserInput2;
								if (UserInput2 == 1) {
									UserSetFile("WRITE", currentSetting ,"T");   // 切换为“开启”
									ScilentShut = true;
									ShutDown_ThreadMode = true;
									OnlyRunShutThread = 0;
									if (hMutex == NULL || GetLastError() == ERROR_ALREADY_EXISTS) {
								        // 释放互斥体句柄
								        if (hMutex != NULL) {
								            CloseHandle(hMutex);
								        }
								        // 关闭先前的实例
								        HWND hwnd = FindWindow(NULL, "Your Program Window Title");
								        if (hwnd != NULL) {
								            PostMessage(hwnd, WM_CLOSE, 0, 0);
								        }
								        // 启动一个新的实例
								        ShellExecute(NULL, "open", PROGRAM_FILENAME, NULL, NULL, SW_SHOWNORMAL);
								        return 0;
								    }
								}
								else{
									printf("\n 取消开启");
									Sleep(500);
									continue;
								}
							};
							continue;
						}
						
						if (UserInput == 6) {
							if (UserSetFile("GET",currentSetting) == "T") {  // 如果当前设置为“开启”
								UserSetFile("WRITE", currentSetting ,"F"); // 切换为“关闭”
							} else {  // 如果当前设置为“关闭”
								UserSetFile("WRITE", currentSetting ,"T");   // 切换为“开启”
							}
							
							HANDLE hThread = NULL;
							// 当需要停止线程时
							if (hThread != NULL) {
								stopShowWindowThread = true;    // Signal the thread to stop
								WaitForSingleObject(hThread, INFINITE);  // Wait for the thread to exit
								CloseHandle(hThread);   // Close the thread handle
								hThread = NULL;
							}
 
							// 重新启动线程
							stopShowWindowThread = false;
							hThread = CreateThread(NULL, 0, Showwindow_Thread, NULL, 0, NULL);
							cout<<"I am Showwindow_Thread!";
							Sleep(254);
							continue;
						}
						
						if ((UserInput == silentShutdownSettingIndex and UserSetFile("GET","SilentShutdown") == "T") || (UserInput == lockTimeSettingIndex and UserSetFile("GET","Autolock") == "T")) {
							cout << " 请输入更改分钟数： ";
							bool RightStr = true;
							int cinans = 0;
							while (RightStr) {
								UserInput2 = 0;
								cin >> UserInput2;
								cinans = (int) UserInput2;
								if (UserInput2 == cinans && UserInput2 > 0 && UserInput == lockTimeSettingIndex ? : UserInput2 < 10) {
									cinans = (int) UserInput2;
									RightStr = false;
								} else {
									cin.clear();
									cin.ignore(numeric_limits<streamsize>::max(), '\n');
									printf(" 输入错误!你需要输入一个正整数\n 请输入：");
								}
							}
							UserSetFile("WRITE",UserInput == silentShutdownSettingIndex ? "SlientRunTime" : "Autolocktime", std::to_string(UserInput2));
 							if(UserInput == lockTimeSettingIndex){
							 	CreateThread(NULL, 0, AutoLock_Thread, NULL, 0, NULL);	//创建线程
							}
						}
						if (UserInput == refreshSettingIndex || UserInput == minimizeSettingIndex) {
							cout << " 请输入更改秒数： ";
							bool RightStr = true;
							int cinans = 0;
							while (RightStr) {
								UserInput2 = 0;
								cin >> UserInput2;
								cinans = (int) UserInput2;
								if (UserInput2 == cinans && UserInput2 > 0) {
									cinans = (int) UserInput2;
									RightStr = false;
								} else {
									cin.clear();
									cin.ignore(numeric_limits<streamsize>::max(), '\n');
									printf(" 输入错误!你需要输入一个正整数\n 请输入：");
								}
							}
							
							UserSetFile("WRITE",UserInput == refreshSettingIndex ? "ResetShotTime" : "ShowwindowTime", std::to_string(UserInput2));
 
							if (UserInput == refreshSettingIndex){
								hEvent = false;
								CreateThread(NULL, 0, ResetShottime_Thread, NULL, 0, NULL);	//重新创建线程
								hEvent = true;
							}
							printf("\n 更改的秒数为 %d 秒", UserInput2);
							continue;
						}
						 
 
						if (UserInput == settingsDesc.size() + 1) {
							int choice = 0;
							cout << "\n 请选择功能：\n" << endl;
							cout << "   1. 登录" << endl;
							cout << "   2. 更改密码" << endl; // 添加新功能
							cout << "   3. 注销账号" << endl;
							printf("\n 请输入：");
							std::unique_ptr<std::string> s = std::make_unique<std::string>(); // 创建智能指针
					        std::cin >> *s; // 输入数据到智能指针指向的 std::string
					
					        // 验证输入是否符合要求
					        if (s->length() > 1 || (*s)[0] < '0' || (*s)[0] > '3') {
					            printf("\n 错误！无效的输入！");
					            Sleep(500); // 延迟 500 毫秒
					            system("cls"); // 清屏
					            continue; // 继续循环等待正确输入
					        }
			 
							// 转换输入为整数
							choice = (*s)[0] - '0';
							switch (choice) {
								case 1:
									if (checkFileExists()) {
										system("cls");
										//UserSetFile(1, 0, 1, 0,"");  // 切换为“开启”
										// 释放互斥体句柄
										CloseHandle(hMutex);
										return main(argc, argv);
									}
									else{
										cout << " 未找到注册用户信息，请先进行注册。" << endl;
										while (!registerUser()) {
										}
									}
									break;
								case 2:
									if (changePassword()) {
										Sleep(1000);
										// 释放互斥体句柄
										CloseHandle(hMutex);
										return main(argc, argv);
									}
									break;
								case 3:
									// 释放互斥体句柄
									CloseHandle(hMutex);
									return main(argc, argv);
								default:
									cout << " 错误：无效的选择。" << endl;
									break;
							}
						}
						if (UserInput == 0) {
							Cbreak = false;
						}
					}
				}
			}
		}
	}
	// 释放互斥体句柄
	CloseHandle(hMutex);
}
